go - 如何在 Golang 中转换其中包含另一个结构的结构?

标签 go struct casting type-conversion type-assertion

我有一个如下所示的模型:

type TeamsKey struct {
    KeyData TeamsKeyData
    Fingerprint string
    Algorithm string
    Encoding string
    Usage string
}

type TeamsKeyData struct {
    KeyId string
    Key string
    Description string
    ExpiresAt string
    CreatedAt string
 }

type Key struct {
    KeyData     KeyData
    Fingerprint string
    Algorithm   string
    Encoding    string
    Usage       string
}

type KeyData struct {
    KeyId       string
    Key         string
    Description string
    ExpiresAt   string
    CreatedAt   string
}

我想将 Key 的实例转换为 TeamsKey。尽管底层结构相同,但我无法转换它。

func main() {
    k := Key{}
    a := TeamsKey(k)
}

我得到的错误:

tmp/sandbox251934449/main.go:46:15: cannot convert k (type Key) to type TeamsKey

当我改变TeamsKeyDataKeyDataTeamsKey struct,我可以毫无问题地转换该结构。

问题是,即使底层结构完全相同,为什么我不能将实例相互转换?

谢谢!

最佳答案

转换项目时,它们具有相同的布局是不够的,它们 need to have the same underlying type for all their fields .

在这种情况下,您能做的最好的事情就是创建一个所需类型的新结构,并使用旧结构中的数据填充其字段。

我对此进行了一些尝试,但我无法做得更好。

我假设两个 KeyData 类型需要不同的方法集?如果情况并非如此,您应该在两个地方使用相同的类型。

关于go - 如何在 Golang 中转换其中包含另一个结构的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46003028/

相关文章:

swift - 在父类(super class)中实现 CodingKey 映射

memory - 在 Arduino 的 EEPROM 中读取和写入结构

java - java中如何将一个对象转换为另一个对象? "javafx.scene.Group cannot be cast to javafx.scene.shape.Rectangle"

c++ - Matrix 中没有 'operator *' 的匹配运算符

c++ - 'iterator' 可以只输入子类 'const_iterator' 吗?

go 项目构建失败 : lfstackPack redeclared in this block

c++ - 从C++ dll调用Go dll

string - 在go中遍历字符串字符的最正确方法是什么

Swift Struct 不符合协议(protocol) Equatable?

inheritance - Golang 和继承