gpt4 book ai didi

go - (*SomeStruct)(nil) 是什么意思?

转载 作者:IT王子 更新时间:2023-10-29 01:25:36 24 4
gpt4 key购买 nike

我试图理解 ORM 库的这段代码,但我无法理解 (*User)(nil) 的含义?第一个括号是指向 User 结构的指针,那么第二个括号代表什么?

type User struct {
Id int64
Name string
Emails []string
}

for _, model := range []interface{}{(*User)(nil), (*Story)(nil)} {
err := db.CreateTable(model, &orm.CreateTableOptions{
// ....
}
}

最佳答案

在 Go 中,nilcan by typed ,因此 *User 类型的 nil 不同于 *Story 类型的 nil。所以 (*User)(nil) 实际上是一个 type conversion这使得类型化的 nil 指针。此外,类型化指针然后根据 CreateTable 隐式转换为 interface{}签名。接口(interface)总是store their type along with the data ,并且可以在运行时使用 reflect 访问该信息, 比如 it happens in ORM .

因为在 Go 中类型不是“一等公民”,即你不能只将类型作为值传递,它们使用类型化的 nil 指针习惯用法,本质上允许提供所需的模型类型作为 CreateTable 的参数,无需创建它的实例或在客户端代码中混淆 reflect

关于go - (*SomeStruct)(nil) 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com