小编典典

复合文字中缺少类型

go

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

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

a := &A{B:{Some: "xxx", Len: 3}}

预计我会遇到错误:

missing type in composite literal

当然,我可以创建一个单独的结构B并通过以下方式对其进行初始化:

type Btype struct {
    Some string
    Len int
}

type A struct {
    B Btype
}

a := &A{B:Btype{Some: "xxx", Len: 3}}

但是它没有第一种方法有用。有没有初始化匿名结构的捷径?


阅读 436

收藏
2020-07-02

共1个答案

小编典典

可转让规则是宽容的,这导致另一种可能性,你可以保留的原始定义匿名类型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)
}

操场


输出量

&main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}
2020-07-02