我们正在使用openapi-generator来生成go-gin-server.这将生成包含类型*interface{}的属性的模型,例如.

type Material struct {
    Id *interface{} `json:"id,omitempty"`
    Reference *interface{} `json:"reference,omitempty"`
}

如果我有一个没有指针的 struct 实例,如何设置这些指针呢?我try 了以下几种方法:

theReturnId := "abc123"
material.Id = &theReturnId

这会产生以下编译错误:

不能将&theReturnID(*字符串类型的值)用作赋值中的*接口{}值:*字符串不实现*接口{}(类型interface{} is pointer to interface, not interface)

theReturnId := "abc123"
*material.Id = theReturnId

这会产生一个运行时错误,即指针为零.

我试过很多其他的方法,但都没有用.我错过了什么吗?谢谢!

推荐答案

您几乎从不需要指向接口的指针.您应该将接口作为值传递,但是底层数据仍然可以是指针.

您需要重新考虑您的设计/代码生成技术,以避免使用这种方法,因为它不是惯用的围棋.


如果您仍想使用它,请使用类型为interface{}的变量并获取其地址.您在示例中使用的方法是不正确的,因为theReturnId是字符串类型,获取其地址将意味着*string类型,这不能直接分配给*interface{}类型,因为围棋是一种强类型语言

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相关问答推荐

从Kafka到Clickhouse的实时消费数据

运行add. inf,这样我们就可以在app.conf中使用. inf参数了?

Golang应用程序:所请求的资源上不存在HTTP-Control-Allow-Origin标头

切换选项卡时,Goland IDE中的光标自动转移

GORM:一个表的两个外键

死锁 - 所有 goroutine 都处于睡眠状态(即使使用等待组)

获取 nil 指针类型的 reflect.Value

自定义 Fyne 自适应网格布局

如何在 gocql 中设置最大池大小?

assert: mock: I don't know what to return because the method call was unexpected 在 Go 中编写单元测试时出错

为什么 `append(x[:0:0], x...)` 将切片复制到 Go 中的新后备数组中?

如何将一片 map 转换为一片具有不同属性的 struct

如何在 Docker 容器中使用私有存储库进行身份验证

在恒等函数中将类型 T 转换为类型 U

Golang Getrlimit 返回与 ulimit 不同的值

如何在 GORM 中获取字段值

Go 中 SDL Surface 的 OpenGL 纹理

Go AST:获取所有 struct

如何正确为 Go 中的值设置多种类型?

防止在 Go 公用文件夹中列出目录