Golang: Type Conversion and Type Assertion


This note is talking about Golang Type Conversion and Assertion

Type Conversion Sample 1:

package main

import "fmt"

var (
	i int
	f float64
	u uint
)

func main() {

	i := 42
	f := float64(i)
	u := uint(f)

	fmt.Printf("%d | %f | %d", i, f, u)
}

Output:

42 | 42.000000 | 42

Type Assertion Sample 2:

package main

package main

import (
	"fmt"
	"time"
)

func timeMap(y interface{}) {
	z, ok := y.(map[string]interface{})
	if ok {
		z["updated_at"] = time.Now()
	}
}

func main() {
	foo := map[string]interface{}{
		"Matt": 42,
	}
	timeMap(foo)
	fmt.Println(foo)
}

Output:

map[Matt:42 updated_at:2016-12-25 12:08:55.846672892 +0700 WIB]

*In this step I am still not sure about what the code actually does

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s