doushi7394 2015-04-08 21:06
浏览 49

Golang:零类型的防御性接口

I recently found some go code was running in a test framework where there were some uninitialized variables.

This lead to a panic, which had a stack trace containing some c code at the top.

Is there a way, in functions, that we can concisely detect wether the struct which is referenced as the implementing member is nil? i.e.

func ( d *Dog ) canBark Bool {
      //if d is nil, cryptic exception is thrown.
      //is there a way to defend against this?
}

The error which is thrown is

panic: runtime error: invalid memory address or nil pointer dereference 
[signal 0xb code=0x1 addr=0x0 pc=0x4ec83a] 
goroutine 16 [running]:   
runtime.panic(0x9b7400, 0xf7ddf3) 

It seems that in go, such lower level errors should occur very rarely, maybe never at all...

There might be a Golang way to deal with nil references which don't clutter the code too much with if/else logic. For example, in java, you can wrap a large code segment in a null pointer exception handler.

  • 写回答

2条回答 默认 最新

  • dtdr57046 2015-04-08 21:14
    关注

    You can check for nil and then do whatever:

    func (d *Dog) canBark bool {
        if d == nil {
            // do something useful, maybe? Like log
            // a stack trace for debugging later
            log.Print("Attempt to bark a nil dog!")
            return false
        }
        // do the regular things
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM