go - 设置一个指向空接口(interface)的指针

标签 go openapi-generator

我们正在使用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/

相关文章:

google-app-engine - Go + App Engine 数据存储区 : How to filter out rows that are null?

spring-boot - Spring Boot 应用程序中的错误 - 无法映射重复的端点操作 : [MBean call 'topology' ] to topologyEndpoint

java - 如何在 Open API 3.0 中为 GET API 定义 map 对象

typescript - Openapi Generator 不会生成 readme.md 文件,但仅适用于 typescript-axios 和 typescript-fetch 生成器

java - 更改 Spring openapi-generator-maven-plugin 生成的接口(interface)的返回类型

macos - 如何检测什么条形码扫描仪(模拟为USB键盘输入)数据来自

google-app-engine - 您能解释一下应用程序引擎上下文接口(interface)是什么吗?

mongodb - 如何在 golang 中 $push 嵌套数组?

typescript - 如何从 OpenAPI 3.0 规范生成 Express + TypeScript API?

go - 具有接口(interface)成员和指针接收器的结构