gpt4 book ai didi

go - 在 golang 中,可以使用任何类型的 slice 变量的结构吗?

转载 作者:数据小太阳 更新时间:2023-10-29 03:34:45 24 4
gpt4 key购买 nike

简单的 golang 应用给出以下错误

.\test.go:13: cannot use ds (type Data_A) as type []interface {} in field value

下面的代码

package main

type Data_A struct {
a string
}

type DTResponse struct {
Data []interface{} `json:"data"`
}

func main() {
ds := Data_A{"1"}
dtResp := &DTResponse{ Data:ds}

print(dtResp)
}

我想要一个带有任何类型 slice 变量的结构。使用 struct{} 会产生同样的错误。

在 Java 中,我可以使用 Object,因为它是任何对象的父对象。但是我在golang中找不到这样的。

如有任何帮助,我们将不胜感激。

最佳答案

是的,作为可以包含任意值的 interface{} 的一部分。

var s = []interface{}{1, 2, "three", SomeFunction}
fmt.Printf("Hello, %#v \n", s)

输出:

Hello, []interface {}{1, 2, "three", (func())(0xd4b60)} 

https://play.golang.org/p/MQMc689StO

但我不建议用这种方式模拟动态类型的语言(如 Python、JavaScript、PHP 等)。最好使用 Go 的所有静态类型优势,并将此功能留作最后的手段,或作为用户输入的容器。只是为了接收它并转换为严格类型。

关于go - 在 golang 中,可以使用任何类型的 slice 变量的结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47427494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com