1, create new project "test9_interface"
$ cd ~/project
$ mkdir test9_interface
$ cd test9_interface
$ touch interface.go
2,add following lines in “interface.go”
package main
import (
"fmt"
"time"
)
type example interface {
describe()
change()
}
type empty interface {}
type introduce interface {
getType()
}
type operation interface {
example
introduce
}
type workTime struct {
start time.Time
finish time.Time
}
type subwayRoute struct {
start string
finish string
}
func main() {
// TEST 1, interface and struct
var startT, finishT time.Time
Seoul, err := time.LoadLocation("Asia/Seoul")
if err == nil {
startT = time.Date(2020, time.December, 12, 25, 8, 0, 0, Seoul)
finishT = time.Date(2020, time.December, 12, 25, 17, 0, 0, Seoul)
}
var _w = workTime{startT, finishT}
var _s = &subwayRoute{"Unseo", "Incheon"}
_w.describe()
_s.describe()
// TEST 2, interface as value
var e example
e = _w // struct workTime implements all methods of interface example
e.change()
e.describe()
e = _s // struct subwayRoute implements all methods of interface example
e.change()
e.describe()
// TEST 3, empty interface, all type parameter have method as empty interface
display("hello")
display(_w)
display(e)
// TEST 4, interface default value is nil
var _e example
if _e == nil {
fmt.Printf("interface default value: %T, %v\n", _e, _e)
} else {
_e.describe()
}
// TEST 5, single struct implements several interface
var _s1 = &subwayRoute{"start-station", "terminal-station"}
_s1.describe()
_s1.change()
_s1.getType()
// TEST 6, insert interface to another one
var _o operation
_o = _s1
_o.describe()
_o.change()
_o.getType()
}
func (w workTime) describe() {
fmt.Printf("workTime: %T, %v\n", w, w)
}
func (w workTime) change() {
Seoul, _ := time.LoadLocation("Asia/Seoul")
w.start = time.Date(2020, time.December, 12, 25, 9, 0, 0, Seoul)
w.finish = time.Date(2020, time.December, 12, 25, 18, 0, 0, Seoul)
}
func (s *subwayRoute) describe() {
fmt.Printf("subwayRoute: %T, %v\n", s, s)
}
func (s *subwayRoute) change() {
s.start = "Seoul"
s.finish = "Incheon"
}
func (s *subwayRoute) getType() {
fmt.Printf("%T, %T, %T\n", s, s.start, s.finish)
}
func display(e empty) {
fmt.Printf("empty interface: %T, %v\n", e, e)
}
3, run “interface.go”
go run interface.go
you should get result like this:
workTime: main.workTime, {{0 63743386080 0xc000108000} {0 63743386620 0xc000108000}}
subwayRoute: *main.subwayRoute, &{Unseo Incheon}
workTime: main.workTime, {{0 63743386080 0xc000108000} {0 63743386620 0xc000108000}}
subwayRoute: *main.subwayRoute, &{Seoul Incheon}
empty interface: string, hello
empty interface: main.workTime, {{0 63743386080 0xc000108000} {0 63743386620 0xc000108000}}
empty interface: *main.subwayRoute, &{Seoul Incheon}
interface default value: <nil>, <nil>
subwayRoute: *main.subwayRoute, &{start-station terminal-station}
*main.subwayRoute, string, string
subwayRoute: *main.subwayRoute, &{Seoul Incheon}
*main.subwayRoute, string, string