新的匿名结构指针

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

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).

huangapple
  • 本文由 发表于 2022年3月29日 21:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/71662788.html
匿名

发表评论

匿名网友

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

确定