如何在Golang中正确初始化一个结构体中的结构体指针

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

How to Init a pointer of struct in a struct properly in Golang

问题

我有一个生成的结构体,看起来像这样:

  1. type a_weird_struct struct {
  2. a *string
  3. b *string
  4. c *struct {
  5. d *int
  6. e *int
  7. f *int
  8. }
  9. }

如何正确初始化这个结构体?特别是结构体指针 c

英文:

I have a generated struct that looks like this:

  1. type a_weird_struct struct {
  2. a *string
  3. b *string
  4. c *struct {
  5. d *int
  6. e *int
  7. f *int
  8. }
  9. }

What is the proper way to initialize this struct? Specifically, the struct pointer c.

答案1

得分: 1

尝试像这样初始化指针:

  1. func initPointer() {
  2. astr, bstr := "xxxx", "yyyy"
  3. dint, eint, fint := 1, 2, 3
  4. x := &a_weird_struct{
  5. a: &astr,
  6. b: &bstr,
  7. c: &(struct {
  8. d *int
  9. e *int
  10. f *int
  11. }{
  12. d: &dint,
  13. e: &eint,
  14. f: &fint,
  15. }),
  16. }
  17. fmt.Println(x)
  18. }

请注意,这只是一个示例代码,具体的上下文可能会有所不同。

英文:

try to init pointer like this

  1. func initPointer() {
  2. astr, bstr := "xxxx", "yyyy"
  3. dint, eint, fint := 1, 2, 3
  4. x := &a_weird_struct{
  5. a: &astr,
  6. b: &bstr,
  7. c: &(struct {
  8. d *int
  9. e *int
  10. f *int
  11. }{
  12. d: &dint,
  13. e: &eint,
  14. f: &fint,
  15. }),
  16. }
  17. fmt.Println(x)
  18. }

答案2

得分: -1

  1. func PointOf[T any](value T) *T {
  2. return &value
  3. }
  4. a_weird_struct{
  5. a: PointOf("a"),
  6. b: PointOf("b"),
  7. c: &struct{d *int; e *int; f *int}{
  8. PointOf(1),
  9. PointOf(2),
  10. PointOf(3),
  11. },
  12. }
  1. func PointOf[T any](value T) *T {
  2. return &value
  3. }
  4. a_weird_struct{
  5. a: PointOf("a"),
  6. b: PointOf("b"),
  7. c: &struct{d *int; e *int; f *int}{
  8. PointOf(1),
  9. PointOf(2),
  10. PointOf(3),
  11. },
  12. }
英文:
  1. func PointOf[T any](value T) *T {
  2. return &value
  3. }
  4. a_weird_struct{
  5. a: PointOf("a"),
  6. b: PointOf("b"),
  7. c: &struct{d *int; e *int; f *int}{
  8. PointOf(1),
  9. PointOf(2),
  10. PointOf(3),
  11. },
  12. }

huangapple
  • 本文由 发表于 2016年10月27日 15:14:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/40278412.html
匿名

发表评论

匿名网友

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

确定