复合文字中缺少类型

tac*_*bot 24 struct go

type A struct {
    B struct {
        Some string
        Len  int
    }
}
Run Code Online (Sandbox Code Playgroud)

简单的问题.如何初始化这个结构?我想做这样的事情:

a := &A{B:{Some: "xxx", Len: 3}} 
Run Code Online (Sandbox Code Playgroud)

预计我会收到一个错误:

missing type in composite literal
Run Code Online (Sandbox Code Playgroud)

当然,我可以创建一个单独的struct B并以这种方式初始化它:

type Btype struct {
    Some string
    Len int
}

type A struct {
    B Btype
}

a := &A{B:Btype{Some: "xxx", Len: 3}}
Run Code Online (Sandbox Code Playgroud)

但它没有第一种方式那么有用.是否有初始化匿名结构的快捷方式?

zzz*_*zzz 15

该可转让规则被原谅的匿名类型导致另一种可能性,你可以保留的原始定义A,同时允许该类型的复合短文字写入.如果你真的坚持这个B领域的匿名类型,我可能会写一些类似的东西:

package main

import "fmt"

type (
        A struct {
                B struct {
                        Some string
                        Len  int
                }
        }

        b struct {
                Some string
                Len  int
        }
)

func main() {
        a := &A{b{"xxx", 3}}
        fmt.Printf("%#v\n", a)
}
Run Code Online (Sandbox Code Playgroud)

操场


产量

&main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}
Run Code Online (Sandbox Code Playgroud)

  • 如果字段值是结构的切片,则会失败 (2认同)

小智 10

这样做:

type Config struct {
    Element struct {    
        Name string 
        ConfigPaths []string 
    } 
}
Run Code Online (Sandbox Code Playgroud)
config = Config{}
config.Element.Name = "foo"
config.Element.ConfigPaths = []string{"blah"}
Run Code Online (Sandbox Code Playgroud)