data-structures - Golang - 结构之间的转换

标签 data-structures go casting

我有两个结构

type A struct {
    a int
    b string
}

type B struct {
    A
    c string
    // more fields
}

我想将类型 A 的变量转换为类型 B(A 只定义了对某些部分至关重要的基本字段,另一方面 B 包含“完整”数据)。

在 Go 中是否可行,还是我必须手动复制字段(或创建一个方法 A.GetB() 或类似的方法并使用它来将 A 转换为 B)?

最佳答案

转换是指:

func main() {
    // create structA of type A
    structA := A{a: 42, b: "foo"}

    // convert to type B
    structB := B{A: structA}
}

关于data-structures - Golang - 结构之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37724757/

相关文章:

java - 找到两个链表的交点?

python - Allen Downey 的 Think Python 第 12 章(元组)的练习 6

delphi - 哪个 Delphi 数据结构可以保存唯一整数列表?

c++ - 如何将指针转换为 int

java - 在没有 If 语句的情况下在 Java 中将 boolean 值转换为整数

algorithm - 寻找链接词

python - 如何在go或python中将结构写入文件?

Golang 不会重新编译某些文件

go - 如何从字符串中获取有效的 IETF 语言标记

c++ - 解析二进制文件。什么是现代方式?