缺少复合字面量中的类型

huangapple go评论80阅读模式
英文:

Missing type in composite literal

问题

a := &A{B: struct{ Some string; Len int }{Some: "xxx", Len: 3}}

英文:
type A struct {
    B struct {
        Some string
        Len  int
    }
}

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

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

Expectedly I'm getting an error:

missing type in composite literal

Sure, I can create a separated struct B and initialize it this way:

type Btype struct {
    Some string
    Len int
}

type A struct {
    B Btype
}

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

But it not so useful than the first way. Is there a shortcut to initialize anonymous structure?

答案1

得分: 26

分配规则对于匿名类型是宽容的,这导致另一种可能性,即您可以保留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)
}

Playground


输出

&main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}
英文:

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

答案2

得分: 9

这样做:

type Config struct {
	Element struct {	
		Name string 
		ConfigPaths []string 
	} 
}
config = Config{}
config.Element.Name = "foo"
config.Element.ConfigPaths = []string{"blah"}
英文:

do it this way:

type Config struct {
	Element struct {	
		Name string 
		ConfigPaths []string 
	} 
}
config = Config{}
config.Element.Name = "foo"
config.Element.ConfigPaths = []string{"blah"}

答案3

得分: 2

这是我认为更简单的方式:

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

a := A{
	struct {
		Some string
		Len  int
	}{"xxx", 3},
}
fmt.Printf("%+v", a)
英文:

This is simpler imo:

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

a := A{
	struct {
		Some string
		Len  int
	}{"xxx", 3},
}
fmt.Printf("%+v", a)

huangapple
  • 本文由 发表于 2013年7月29日 05:04:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/17912893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定