Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.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
Pointers 将类型为*[]foo的变量转换为*[]bar_Pointers_Go_Struct_Slice - Fatal编程技术网

Pointers 将类型为*[]foo的变量转换为*[]bar

Pointers 将类型为*[]foo的变量转换为*[]bar,pointers,go,struct,slice,Pointers,Go,Struct,Slice,我想在两个相同的结构之间转换。主要是在两个结构上使用不同的json标记。有办法吗?我试过上面的例子,也试过用指针片代替指向片的指针的例子。无效。语言规范允许在具有相同字段(忽略标记)的结构类型之间切换 因此,创建另一个切片(类型为[]bar),并使用一个简单的循环来填充它,将每个foo转换为bar: type foo struct { Field1 int Field2 string } type bar struct { Field1 int Field2 s

我想在两个相同的结构之间转换。主要是在两个结构上使用不同的json标记。有办法吗?我试过上面的例子,也试过用指针片代替指向片的指针的例子。无效。

语言规范允许在具有相同字段(忽略标记)的结构类型之间切换

因此,创建另一个切片(类型为
[]bar
),并使用一个简单的循环来填充它,将每个
foo
转换为
bar

type foo struct {
    Field1 int
    Field2 string
}

type bar struct {
    Field1 int
    Field2 string
}

func main() {
    x := foo{1, "Hello"}
    y := bar(x)

    a := [...]foo{x, x}
    b := a[:]

    c := (*[]bar)(&b)

    fmt.Println(x, y, a, b, c)
}
试穿一下

请注意,由于我们正在分配结构值,因此所有字段都将被复制。如果不想复制整个结构,可以使用指针:

foos := []foo{
    {1, "Hello"},
    {2, "Bye"},
}

bars := make([]bar, len(foos))
for i, f := range foos {
    bars[i] = bar(f)
}

fmt.Println(foos, bars)
这将输出(在上尝试):


从输出中可以看到,
foos
bar
切片中的指针是相同的,但是第一个包含类型为
*foo
的值,后面的类型为
*bar

的值请尝试以下操作:同时确保您真正理解使用切片指针的原因。你几乎从不需要这样的东西。这涉及到复制所有的foo吗?我也可以用指针吗?
foos := []*foo{
    {1, "Hello"},
    {2, "Bye"},
}

bars := make([]*bar, len(foos))
for i, f := range foos {
    bars[i] = (*bar)(f)
}

fmt.Println(foos, bars)
for i := range foos {
    fmt.Println(foos[i], bars[i])
}
[0x40a0e0 0x40a0f0] [0x40a0e0 0x40a0f0]
&{1 Hello} &{1 Hello}
&{2 Bye} &{2 Bye}