↓ Skip to main content
Notes

Nil Interface

·2 mins

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 {
     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

— THE – END —
#

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Metric Beat

All right, its been a busy week and finally some time at hand to write about something I have been doing. Mostly I am working on ELK stack these days, securing, validating, data analytics etc. Today, had the opportunity to go the Secure Elastic way, by enabling the TLS for secure communication within Nodes (Elastic cluster) and finally setup a Metric beat to get the status of the node.

Securing Elastic

·4 mins
Security is integral to every and all the tasks in a shared environment. In ELK if you have setup a cluster which is accessible to all; anyone can make modifications which may or may not impact the other users.