Interface
To implement an interface in Go, we just need to implement all the methods in the interface.
Sample
This samples covers
- blank interface
- prepare interface
- implement in struct
package main import ( "fmt" "reflect" ) type InterfaceSample interface{} type InterfaceZ interface { setValue(v int) getValue() int } type InterfaceImpl struct { Value int Name string } func (i *InterfaceImpl) setValue(v int) { i.Value = v } func (i *InterfaceImpl) getValue() int { return i.Value } func main() { var i1 InterfaceZ fmt.Println(i1) i1 = new(InterfaceImpl) fmt.Println(i1) i1.setValue(3) fmt.Println(i1.getValue()) // NO i1.Name = "" // Blank Interface var i2 InterfaceSample fmt.Println(i2) i2 = 3 fmt.Println(i2) i2 = new(InterfaceImpl) fmt.Println(i2) fmt.Println(reflect.TypeOf(i2)) }
blank interface is powerful, can insert anything.
コメント