英文:
Initializing a field inside an anonymous struct
问题
给定这个匿名结构体:
var myMap struct {
list map[string]string
someStuff *some.Object
}
我可以在一个声明中初始化list
和someStuff
吗?
这样是不起作用的:
var myMap struct {
list map[string]string = make(map[string]string)
someStuff *some.Object = &some.Object{}
}
英文:
Given this anonymous struct:
var myMap struct {
list map[string]string
someStuff *some.Object
}
Can I initialize the list
and someStuff
in one declaration?
This doesn't work:
var myMap struct {
list map[string]string = make(map[string]string)
someStuff *some.Object = &some.Object{}
}
答案1
得分: 12
这是翻译好的内容:
这是你要的代码示例:
var myMap = struct {
list map[string]string
str string
}{
list: map[string]string{"hello":"string"},
str: "myString",
}
你也可以这样写:
var myMap = struct {
list map[string]string
str string
}{map[string]string{"hello":"string"}, "myString"}
这是一个可运行的示例:[Go PlayGround](https://play.golang.org/p/j1l2epoB_s)。
所以你声明了一个结构体,然后在花括号中初始化它。(我是从这个[旧的 Go talk](https://talks.golang.org/2012/10things.slide#3)中学到的。)
英文:
Here you go:
var myMap = struct {
list map[string]string
str string
}{
list: map[string]string{"hello":"string"},
str: "myString",
}
You can also do it this way:
var myMap = struct {
list map[string]string
str string
}{map[string]string{"hello":"string"}, "myString"}
And a working example: <kbd>Go PlayGround</kbd>.
So you declare your structure and then in curly braces you initiate it. (I learned it from this old go talk.)
答案2
得分: 7
是的,你可以这样做。看看这个例子:
package main
import "fmt"
func main() {
myMap := struct {
list map[string]string
someStuff interface{}
}{
list: make(map[string]string),
someStuff: 2,
}
fmt.Println(myMap)
}
英文:
Yes, you can do this. Look at this example:
package main
import "fmt"
func main() {
myMap := struct {
list map[string]string
someStuff interface{}
}{
list: make(map[string]string),
someStuff: 2,
}
fmt.Println(myMap)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论