英文:
new anonymous struct pointer
问题
我是你的中文翻译助手,以下是翻译好的内容:
我刚开始学习Go语言,发现定义单独的类型结构不如将结构体嵌套在另一个结构体中看起来美观。如果我有这样的结构体:
var out outter
type outter struct {
a int
b string
...
s map[string]*struct{
sa int
sb string
...
}
}
那么我可以通过简单的 out.s["abc"].sa
来访问 s
映射中的值...如果我只能以某种方式向这个匿名结构体中插入值就好了。所以我的问题是如何在我的函数中向映射 s
中插入新值。
out.s["abc"] = new(typeof(*out.s[""])) // 类似这样的操作
英文:
I am new to Go, and defining separate type structs is less pretty than having structs one inside other, and if i have struct like this
var out outter
type outter struct {
a int
b string
...
s map[string]*struct{
sa int
sb string
...
}
}
Then I could access s
map for reading with simple out.s["abc"].sa
... if I could only somehow insert values to such anonymous struct. So my question is how to insert new values in map s
somewhere in my functions.
out.s["abc"] = new( typeof(*out.s[""]) ) // something like that
答案1
得分: 1
使用匿名结构体进行分配可能会有些繁琐,但并不难:
out.s = make(map[string]*struct {
sa int
sb string
})
out.s["abc"] = &struct {
sa int
sb string
}{
sa: 1,
sb: "hello",
}
完整代码请参考:https://go.dev/play/p/HVU_tQtEQ6Q。
正如 @JimB 指出的,如果给结构体命名,这将变得更加容易:
type outter struct {
a int
b string
s map[string]*inner
}
type inner struct {
sa int
sb string
}
在这种情况下,你可以这样写:
out.s = make(map[string]*inner)
out.s["abc"] = &inner{
sa: 1,
sb: "hello",
}
代码请参考:https://go.dev/play/p/65yWNioBSBm。
英文:
With the anonymous struct the allocations are tedious but not difficult:
out.s = make(map[string]*struct {
sa int
sb string
})
out.s["abc"] = &struct {
sa int
sb string
}{
sa: 1,
sb: "hello",
}
(full code at https://go.dev/play/p/HVU_tQtEQ6Q).
As @JimB pointed out, this gets much easier, if you name the struct:
type outter struct {
a int
b string
s map[string]*inner
}
type inner struct {
sa int
sb string
}
In this case you can write
out.s = make(map[string]*inner)
out.s["abc"] = &inner{
sa: 1,
sb: "hello",
}
(code at https://go.dev/play/p/65yWNioBSBm).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论