英文:
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)
}
输出
&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)
}
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论