登录
首页 >  Golang >  Go问答

创建一个指向空接口的指针

来源:stackoverflow

时间:2024-02-13 14:24:22 255浏览 收藏

从现在开始,努力学习吧!本文《创建一个指向空接口的指针》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

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

这会产生指针为零的运行时错误。

我尝试了很多其他方法,但没有成功。我在这里缺少什么?谢谢!


正确答案


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

您需要重新考虑您的设计/代码生成技术,不要使用这种方法,因为它不是惯用的 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)
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>