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.

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
}

Sure:

func ( d *Dog ) bool {
    if d ==  nil {
        // a nil dog can't bark
        return false
    }
}

It's entirely possible to use methods on a nil struct. However, a nil interface is another story. You can't defend against that, because there's no type to call a method on.

type Barker interface {
    CanBark() bool
}

var dog Barker
//panics
dog.CanBark()

In go, it's a programming error to improperly initialize a data structure, and methods can panic. If a type value is returned to you from a function or a method, there is generally an error value returned as well indicating whether the first value can be used.