使用openapi-generator生成的Go-Gin模型*interface{}字段赋值问题
为
*interface{}类型的结构体字段赋值问题 我们用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
运行时panic:指针为nil
问题原因
- 编译错误原因:
*string和*interface{}是完全不同的类型。interface{}可以容纳任意值,但*interface{}是指向interface{}类型的指针,和指向具体类型(如*string)的指针类型不兼容,Go不允许直接赋值。 - 运行时错误原因:
material.Id初始为nil指针,直接解引用nil指针会触发Go的运行时panic,这是语言的基础约束。
正确赋值方法
方法一:先创建interface{}变量再取指针
// 将字符串值存入interface{}类型变量 idValue := interface{}("abc123") // 把变量的指针赋值给结构体字段 material.Id = &idValue
方法二:先初始化指针再赋值
// new(interface{}) 创建一个指向空interface{}的非nil指针 material.Id = new(interface{}) // 解引用指针并赋值 *material.Id = "abc123"
这两种方法都能正确完成赋值,避免编译或运行时错误。
内容的提问来源于stack exchange,提问作者Chris Wallis
相关产品推荐
相关产品推荐

