Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在golang中,可以使用任何类型的slice变量构造结构吗?_Go - Fatal编程技术网

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

在golang中,可以使用任何类型的slice变量构造结构吗?,go,Go,简单的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 := Da

简单的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,因为它是任何对象的父对象。但我在戈朗找不到这样的


任何帮助都将不胜感激。

是的,作为
接口{}
的一部分,它可以保存任何任意值

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

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

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

键入 Go是一种强显式类型的语言,因此不能用一种类型的对象替换另一种类型的对象(它已经以这种方式编译)。另外,当您使用
类型数据结构{…
时,您定义了名为
数据结构
[]的新类型。接口{}
数据结构{/code>是完全不同的类型,这些类型(与任何其他类型一样)不可互换。注意,即使是
接口{}
不能与任何东西互换。您可以在函数中传递任何类型,例如
func f(a interface{}){…
,但在函数中,您将拥有确切的
interface{}
类型,您应该断言它以正确使用

修正#1 修正2
可能是混淆的原因:struct不是slice或array。

请参阅。重复。试试这个:它对我帮助很大。谢谢你们两位
package main

type Data_A struct {
    a string
}

type DTResponse struct {
    Data Data_A `json:"data"`
}

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

    print(dtResp)
}
package main

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

func main() {
    ds := []interface{}{"1"}
    dtResp := &DTResponse{ Data:ds}

    print(dtResp)
}