Missing type in composite literal

前端 未结 2 748
日久生厌
日久生厌 2020-11-28 12:41
type A struct {
    B struct {
        Some string
        Len  int
    }
}

Simple question. How to initialize this struct? I would like to do somet

相关标签:
2条回答
  • 2020-11-28 13:01

    do it this way:

    type Config struct {
        Element struct {    
            Name string 
            ConfigPaths []string 
        } 
    }
    
    config = Config{}
    config.Element.Name = "foo"
    config.Element.ConfigPaths = []string{"blah"}
    
    0 讨论(0)
  • 2020-11-28 13:02

    The assignability rules are forgiving for anonymous types which leads to another possibility where you can retain the original definition of A while allowing short composite literals of that type to be written. If you really insist on an anonymous type for the B field, I would probably write something like:

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

    Playground


    Output

    &main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}
    
    0 讨论(0)
提交回复
热议问题