English 中文(简体)
如果参照的构件具有零点,如何以零值开始构造
原标题:How to initialize struct with its zero values if referenced struct has nil pointers
  • 时间:2023-12-06 13:44:59
  •  标签:
  • go

I don t know if there following if possible. I have:

type A struct {
  Val int
}

以及

type B struct {
  Val *int
}

接着,我有这一努力。

func main() {
  b := B{Val: new(int)}
  *b.Val = 1

  a := A{Val: *b.Val}
}

What I want to achieve is that the variable a gets initialized with its zero values, hence its Val being 0 in case *b.Val = nil without having to check with an if condition. This is a very simplified version 以及 the reason I am trying to do this is that my B struct has many properties that might or might not be filled by different entities. Such properties make more sense as nil in case they are not filled 以及 I am trying to avoid checking with an if condition for each one of them if they are nil before assigning their non-nil value or the zero value to the properties of A

问题回答

只要你开始做任何事情,就自动产生有违约价值的变数。 您可以简单地使用下文中任何一个提到的内容:

a := new(A)
a := A{}
var a A

以上所有因素都将使其变数变得零。





相关问题
minimum work size of a goroutine [closed]

Does anyone know approximately what the minimum work size is needed in order for a goroutine to be beneficial (assuming that there are free cores for the work to be offloaded to)?

How do you get the terminal size in Go?

How do I get the terminal size in Go. In C it would look like this: struct ttysize ts; ioctl(0, TIOCGWINSZ, &ts); But how to i access TIOCGWINSZ in Go

What do you use to write Go [closed]

I know its a bit too early, but I ve been trying out Go (Google s Programming Language) and its kindof annoying to write code in gedit. So, my question: What do you use to experiment with Go?

Shared memory vs. Go channel communication

One of Go s slogans is Do not communicate by sharing memory; instead, share memory by communicating. I am wondering whether Go allows two different Go-compiled binaries running on the same machine to ...

Embedding instead of inheritance in Go

What is your opinion of this design decision? What advantages does it have and what disadvantages? Links: Embedding description

热门标签