The Scan method supports converting query results into a struct or struct array. The Scan method will automatically identify the type of conversion to execute based on the given parameter type.

struct Object

The Scan method supports converting query results into a struct object. The query result should be a specific single record, and the pointer parameter should be the pointer address of the struct object (*struct or **struct). For example:

  1. type User struct {
  2. Id int
  3. Passport string
  4. Password string
  5. NickName string
  6. CreateTime *gtime.Time
  7. }
  8. user := User{}
  9. g.Model("user").Where("id", 1).Scan(&user)

Or

  1. var user = User{}
  2. g.Model("user").Where("id", 1).Scan(&user)

The first two methods pre-initialize the object (allocate memory in advance), while the recommended method is:

  1. var user *User
  2. g.Model("user").Where("id", 1).Scan(&user)

This method initializes and allocates memory only when data is queried. Note the difference in usage, especially the difference in parameter types (the first two methods pass a *User type, while this method actually passes a **User type).

struct Array

The Scan method supports converting multiple query results into a []struct/[]*struct array. The query result should be a result set composed of multiple records, and the pointer should be the pointer address of the array. For example:

  1. var users []User
  2. g.Model("user").Scan(&users)

Or

  1. var users []*User
  2. g.Model("user").Scan(&users)