Nil Interface – GoLang

Saurabh Sharma

An interface in Golang is a set of methods and a type.

What is the purpose of Nil interface in GO-lang

A nil interface value holds neither value nor concrete type.

type NilI interface {

Just defined an interface with a simple function NoFunction

func main() {
    NilI i

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?


An empty interface that specifies zero methods.

An empty interface is used for unknown types.

func Printf(format string, a ...interface{}) (n int, err error)

var i interface{}
fmt.Printf("(%v, %T)\n", i, i)

(<nil>, <nil>)

if, we assign 
i = 42

(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.


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.

var i interface{} = "simple"

s := i.(string)


s, ok := i.(string)
fmt.Println(s, ok)

simple true

f, ok := i.(int)
fmt.Println(f, ok)

panic: interface conversion: interface {} is string, not float64

— THE – END —

Leave a Reply

Your email address will not be published. Required fields are marked *