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)
}
3.88
8
type Shape interface {
area() float64
perimeter() float64
}
Thank you!
8
0
4.3
10
The interface is a collection of methods as well as it is a custom type.
Thank you!
10
0
Are there any code examples left?
New code examples in category Go
-
Go 2022-03-27 22:30:23 golang check if ip is v6
-
Go 2022-03-27 16:20:18 make image go to center of page
-
Go 2022-03-24 15:20:01 why does my discord bot not work when i take code from googl
-
Go 2022-03-21 18:40:22 pass method as props vue
-
Go 2022-03-19 23:40:33 reverse a string in golang
-
Go 2022-03-18 12:45:06 golang while loop
-
Go 2022-03-17 19:30:08 instancing in godot
-
Go 2022-03-17 09:55:17 brew upgrae golang-migrate
-
Go 2022-03-17 06:15:06 Tushar Jadhav
-
Go 2022-03-17 00:00:12 golang cwd