go interfaces explained code example

Example 1: golang interface

package main

import (
	"fmt"
)

type Pricing interface {
	getDiscount() float32
}

type Address interface {
	getAddress() string
}

// nested struct
type ShowRoom struct {
	address    string
	location   string
	postalcode int
}

// sub nested struct
type Car struct {
	id       int
	name     string
	price    float32
	showroom ShowRoom
}

type Book struct {
	Name, Author string
}

func (m Car) getDiscount() float32 {
	return m.price * 0.5
}

func (m Car) getAddress() string {
	return m.showroom.address
}

func getAllDiscount(d Pricing) float32 {
	return d.getDiscount()
}

func getAllAddress(a Address) string {
	return a.getAddress()
}

func main() {

	var SuperCar Car

	var CityName interface{}
	CityName = "jakarta"
	v, ok := CityName.(string)

	var users = []map[string]interface{}{
		{"name": "monkey d lufy", "age": 19},
		{"name": "trafagar d law", "age": 23},
		{"name": "nico robin", "age": 20},
	}

	SuperCar.id = 1
	SuperCar.name = "lambogini"
	SuperCar.price = 1.500000000
	SuperCar.showroom.address = "jl.nusantara kap 50 - 51"
	SuperCar.showroom.location = "depok"
	SuperCar.showroom.postalcode = 163353

	SuperCar.id = 2
	SuperCar.name = "mc.claren"
	SuperCar.price = 2.500000000
	SuperCar.showroom.address = "jl.kalimulya kap 200 - 2001"
	SuperCar.showroom.location = "depok"
	SuperCar.showroom.postalcode = 163334

	if !ok {
		fmt.Printf("failed to read assertion type with interface %#v \n", v)
		fmt.Printf("failed to read assertion type with interface status %#v \n", ok)
	} else {
		fmt.Printf("successfully read assertion type with interface %#v \n", v)
		fmt.Printf("successfully read assertion type with interface status %#v \n", ok)
	}

	fmt.Println("read nested struct", SuperCar)
	fmt.Println("read nested struct with key", SuperCar.showroom.location)
	fmt.Println("read nested struct discount with interface method", getAllDiscount(SuperCar))
	fmt.Println("read nested struct address with interface method", getAllAddress(SuperCar))
	fmt.Println("read all users with interface assertion", users)
}

Example 2: golang interface

type Shape interface {
    area() float64
    perimeter() float64
}

Tags:

Go Example