Answers for "how to implement any interface in golang"

Go
4

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)
}
Posted by: Guest on March-10-2021
2

golang interface

type Shape interface {
    area() float64
    perimeter() float64
}
Posted by: Guest on June-12-2020

Code answers related to "how to implement any interface in golang"

Browse Popular Code Answers by Language