go - 为什么我们不能将 slice 或映射嵌入到 Go 结构中

标签 go struct composition embedding

我了解到不允许将 slice 或映射嵌入到 Go 结构中。但我发现了两种解决方法:

  • 在结构外声明 slice 或映射并将其嵌入到结构中
    var mySlice []int
    
    type myStruct struct {
      mySlice
    }
    
  • 我不太了解第二种解决方法,但我发现它称为 Composition,它是通过在结构中声明 slice 或 map 时省略 var 关键字来完成的
    type myStruct struct {
      mySlice []int
    }
    

  • 我的第一个问题是,谁能解释为什么我们不能直接将 slice 和映射嵌入到结构中?

    第二个问题:使用第二种解决方法,是否会对性能产生负面影响?

    第三个问题:为什么第一个和第二个解决方法有效?

    最佳答案

    Spec: Struct types:

    A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.



    你不能嵌入像 map[int]string 这样的类型,这是一个匿名类型。 Spec 需要类型名称。即使您可以嵌入它,它也包含括号,这会使它失去作为标识符的资格,并且再次,规范说不合格的类型名称充当字段名称。

    只需为其创建一个新类型,然后您就可以嵌入:
    type mymap map[int]string
    
    type s struct {
        mymap
    }
    

    在结构中嵌入类型时,会省略字段名称。在您的第二次尝试中:
    type myStruct struct {
        mySlice []int
    }
    

    您没有省略字段名称(它是 mySlice ),所以这不是嵌入,它是一个常规的命名字段。

    关于go - 为什么我们不能将 slice 或映射嵌入到 Go 结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61110680/

    相关文章:

    go - 依赖三角

    c++ - SWIG 如何使用 Lua 表从 Lua 中的 c 结构访问字节数组以进行操作

    julia - 在 Julia 中重复一个函数 N 次(组合)

    包含其他对象的类的 C++ 隐式复制构造函数

    go - Golang 中的 HTTP 重定向

    Go:声明一个新变量并从更高的范围覆盖一个变量,如何?

    go - 无法在 '/find/{id}' 下触发 API 端点执行

    c - 错误: Conflicting types in structs pointers

    swift - 只有第一个添加到结构的项目被上传到 firebase

    Mef 导入到 compose 后创建的对象中