doula4096 2018-08-01 21:27
浏览 728

验证是否在struct golang中设置了该字段

I have the following struct:

type Foo struct {
    Bar *FooBar
    Baz *FooBaz
}

type FooBar struct {
    Name string
}

type FooBaz struct {
    Name string
}

How can I access the Baz and Bar in the struct without getting a nil pointer reference when they're not set?

I want something that goes like the below, but I keep getting nil pointer dereference errors.

if Foo.Bar == nil {
  throw error
}

I'm struggling with this!

  • 写回答

2条回答 默认 最新

  • dongshai8330 2018-08-01 21:32
    关注

    You should be able to compare to nil, here's a working example:

    check := func(f Foo) {
      if f.Bar == nil {
        panic("oops!")
      }
      fmt.Println("OK")
    }
    
    foo1 := Foo{Bar: &FooBar{"Alpha"}}
    check(foo1) // OK
    
    foo2 := Foo{}
    check(foo2) // panic: oops!
    

    Note that if you were to modify the "check" function to accept a *Foo and it was called with a nil pointer then that function would itself panic with a "nil pointer dereference runtime error". This might be what is currently happening with your example.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作