gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:42:29 25 4
gpt4 key购买 nike

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)
}

我想在两个相同的结构之间进行转换。主要是在两个结构体上使用不同的json标签。有没有办法做到这一点?我已经尝试过上面的示例以及带有指针 slice 而不是指向 slice 的指针的示例。没有用。

最佳答案

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

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

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

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

fmt.Println(foos, bars)

Go Playground 上尝试一下.

请注意,由于我们要分配结构体值,所以所有字段都会被复制。如果您不想复制整个结构,可以使用指针:

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])
}

这将输出(在 Go Playground 上尝试):

[0x40a0e0 0x40a0f0] [0x40a0e0 0x40a0f0]
&{1 Hello} &{1 Hello}
&{2 Bye} &{2 Bye}

从输出中可以看到,foosbars slice 中的指针是相同的,但第一个包含 *foo< 类型的值,以及后面的 *bar 类型值。

关于pointers - 将 *[]foo 类型的变量转换为 *[]bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58215004/

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