我们正在使用openapi-generator生成 go-gin-server 。这会生成包含 *interface{}
类型属性的模型,例如。
type Material struct {
Id *interface{} `json:"id,omitempty"`
Reference *interface{} `json:"reference,omitempty"`
}
如果我有一个带有 nil 指针的结构实例,如何设置它们?我尝试过以下方法:
theReturnId := "abc123"
material.Id = &theReturnId
这会产生以下编译错误:
cannot use &theReturnId (value of type *string) as *interface{} value in assignment: *string does not implement *interface{} (type interface{} is pointer to interface, not interface)
theReturnId := "abc123"
*material.Id = theReturnId
这会产生指针为零的运行时错误。
我尝试了很多其他方法,但没有成功。我在这里缺少什么?谢谢!
最佳答案
您几乎不需要指向接口(interface)的指针。您应该将接口(interface)作为值传递,但底层数据仍然可以是指针。
您需要重新考虑您的设计/代码生成技术,不要使用这种方法,因为它不是惯用的 Go。
如果您仍想使用它,请使用类型化 interface{}
变量并获取其地址。您在示例中执行的方式不正确,因为 theReturnId
是字符串类型,其地址意味着 *string
类型,无法分配给 *interface{ }
直接输入,因为 Go 是强类型语言
package main
import "fmt"
type Material struct {
Id *interface{} `json:"id,omitempty"`
Reference *interface{} `json:"reference,omitempty"`
}
func main() {
newMaterial := Material{}
var foobar interface{} = "foobar"
newMaterial.Id = &foobar
fmt.Printf("%T\n", newMaterial.Id)
}
关于go - 设置一个指向空接口(interface)的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75050104/