Nil Interface – GoLang
An interface in Golang is a set of methods and a type.
type NilI interface { NoFunction() }
Just defined an interface with a simple function NoFunction
func main() { NilI i i.NoFunction() }
Executing it results in
panic: runtime error: invalid memory address or nil pointer dereference
On the same lines there is empty
interface, but that can hold any value; but what is nil interface suppose to do?
interface{}
An empty interface that specifies zero methods.
An empty interface is used for unknown types.
e.g func Printf(format string, a ...interface{}) (n int, err error) var i interface{} fmt.Printf("(%v, %T)\n", i, i) Outputs (<nil>, <nil>) if, we assign i = 42 Outputs (42, int)
What if you want to evaluate the type of the object or interface?
Type Assertion
A type assertion provides access to an interface value’s underlying concrete value.
t.(type)
type, identifies the concrete value such as int, float etc.
The statement asserts the t holds the concrete type type
. If t does not holds Type type
it will throw a panic error.
another syntactical sugar s, ok := t.(type)
If t has a Type type
then s will have the concrete value and ok
will have value true, else ok
will be false and s
zero value of Type type
.
e.g. var i interface{} = "simple" s := i.(string) fmt.Println(s) Outputs: simple s, ok := i.(string) fmt.Println(s, ok) Outputs: simple true f, ok := i.(int) fmt.Println(f, ok) Outputs: panic: interface conversion: interface {} is string, not float64