英文:
Difference in string and *string in Gorm model declaration
问题
gorm的文档https://gorm.io/docs/models.html中给出了以下示例。
字段Name
和Email
的类型分别为string
和*string
。
这里的主要区别是什么?
另外,如何为存储图像链接列表的Images
字段提供数据类型?
应该是[]string
还是[]*string
?
type User struct {
ID uint
Name string
Email *string
Images []string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
英文:
The docs of gorm https://gorm.io/docs/models.html present an example below.
The field Name
and Email
are described with string
and *string
.
What is the main difference here?
Also how to provide the datatype for the images field storing a list of images link?
Should it be []string
or []*string
?
type User struct {
ID uint
Name string
Email *string
Images []string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
答案1
得分: 9
Go语言对于每种基本数据类型都有默认值。
int -> 0,string -> "",bool -> false等等。所以如果你需要添加空值,或者将空值加载到变量中,它应该是一个指针。否则它会被默认为零值。
指针的默认值在Go中是nil。
而复杂的数据类型,比如切片(slices)和映射(maps),会保留引用。所以它们的默认值是nil。因此,在这个例子中,Images []string
中的images可以是nil。
下面的代码使用指针类型User1
和非指针类型User2
展示了默认值的差异。
package main
import (
"fmt"
"time"
)
type User1 struct {
Email *string
Images []string
Birthday *time.Time
}
type User2 struct {
Email string
Images []string
Birthday time.Time
}
func main() {
user1 := User1{}
user2 := User2{}
fmt.Printf("user1 := %+v \n", user1)
//输出:user1 := {Email:<nil> Images:[] Birthday:<nil>}
fmt.Printf("user2 := %+v \n", user2)
//输出:user2 := {Email: Images:[] Birthday:0001-01-01 00:00:00 +0000 UTC}
}
英文:
Go has default values for every primitive data types.
int -> 0, string -> "", bool -> false likewise. So if you need to add null value, or load null value to a variable, it should be a pointer. Otherwise it is defaulted.
Default value of a pointer is nil in Go.
And complex data types such as slices, maps keep references. So their default value is nil. So, Images []string
here images can be nil.
Below code with pointer types User1
and without pointer types User2
show the difference in default values.
package main
import (
"fmt"
"time"
)
type User1 struct {
Email *string
Images []string
Birthday *time.Time
}
type User2 struct {
Email string
Images []string
Birthday time.Time
}
func main() {
user1 := User1{}
user2 := User2{}
fmt.Printf("user1 := %+v \n", user1)
//Output : user1 := {Email:<nil> Images:[] Birthday:<nil>}
fmt.Printf("user2 := %+v \n", user2)
//Output : user2 := {Email: Images:[] Birthday:0001-01-01 00:00:00 +0000 UTC}
}
答案2
得分: 5
主要的区别在于,如果你使用指针,你可以将一个空值放入数据库中,否则你必须放入一个字符串。
基本上,如果数据库字段可为空,你应该使用指针。
英文:
The main difference is that if you use pointers, you can put a null value into the DB, else you must put a string.
Esentially if the database field is nullable, you should use pointers.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论