gorm模型定义中字段指针和非指针的区别
使用gorm定义模型时,字段类型可以是值类型(如string) 或指针类型(如*string)。
非指针类型(值类型)
非指针类型直接保存字段的值。当对字段进行赋值或修改时,实际上是修改了字段本身,不会影响其他地方对该字段的引用。
指针类型
指针类型保存的是字段的内存地址。当对字段进行赋值或修改时,实际上是修改了指向的内存地址,从而影响了其他地方对该字段的引用。
用法场景
示例
考虑以下模型:
type user struct { id uint name string email *string age uint8 birthday *time.time membernumber sql.nullstring activatedat sql.nulltime createdat time.time updatedat time.time }
user1 := User{Email: "john@example.com"} user2 := user1 fmt.Println(user2.Email) // 输出:"john@example.com" user1.Email = "new.email@example.com" fmt.Println(user2.Email) // 输出:"new.email@example.com" (受影响)