Gorm: Why use pointer type when Declaring Models

Created on 7 Sep 2018  路  2Comments  路  Source: go-gorm/gorm

@see http://gorm.io/docs/models.html

Why type of ('Birthday', 'MemberNumber', 'DeletedAt') used pointer

type User2 struct {
     Name         string
     Age          sql.NullInt64
     Birthday     *time.Time
     Email        string  `gorm:"type:varchar(100);unique_index"`
     Role         string  `gorm:"size:255"` // set field size to 255
     MemberNumber *string `gorm:"unique;not null"` // set member number to unique and not null
     Num          int     `gorm:"AUTO_INCREMENT"` // set num to auto incrementable
     Address      string  `gorm:"index:addr"` // create index with name `addr` for address
     IgnoreMe     int     `gorm:"-"` // ignore this field
     CreatedAt       time.Time
     UpdatedAt       time.Time
     DeletedAt       *time.Time
}

Most helpful comment

non pointer fields are required to have a value, pointers fields could be null

a integer CANNOT be nil, only a value

a pointer to integer CAN be a nil or a value

using a pointers allow the value in the structs be nil, as some columns in database can be nullable

All 2 comments

non pointer fields are required to have a value, pointers fields could be null

a integer CANNOT be nil, only a value

a pointer to integer CAN be a nil or a value

using a pointers allow the value in the structs be nil, as some columns in database can be nullable

non pointer fields are required to have a value, pointers fields could be null

a integer _CANNOT_ be nil, only a value

a pointer to integer _CAN_ be a nil or a value

using a pointers allow the value in the structs be nil, as some columns in database can be nullable

Does this also apply to the official sql package? I ask this because I also notice this behavior but I didn't see any where mentioned in official document, further more, official doc suggests to use the sql.NullXXX type in such scenario.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sredxny picture sredxny  路  3Comments

easonlin404 picture easonlin404  路  3Comments

leebrooks0 picture leebrooks0  路  3Comments

rfyiamcool picture rfyiamcool  路  3Comments

izouxv picture izouxv  路  3Comments