Golang: Collection of structs


This post intended to be my personal note regarding struct collection (map with structs inside):

Link: https://play.golang.org/p/Tj3cpLu-mu

package main

import (
	"fmt"
)

type Animalia struct {
	fart bool
}

type Person struct {
	Animalia // Embedding as extend replacement
	Name, Address string
}

func (p Person) print() {
	if p.Animalia.fart {
		fmt.Println(p.Name, p.Address)
	}
}

type Human interface {
	print()
}

func humanCheck(h Human) {
}

func main() {
	person := Person{
		Animalia{
			true,
		},
		"Yusuf",
		"Jalan No.90",
	}

	person.print()

	// Collection
	people := map[int]Person{
		1: { Animalia{true}, "jhoni", "Jl. Kehidupan no.90"},
		2: { Animalia{true}, "Rhey", "Jl. Kehidupan no.99"},
		3: { Animalia{true}, "Rhona", "Jl. Girang no.77"},
	}

	for _, person := range people {
		humanCheck(person)
		person.print()
	}
}

Output

structoutput1.png

Advertisements

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