package main import "fmt" type IDuck interface { Quack() Walk() } func DuckDance(duck IDuck) { for i := 1; i <= 3; i++ { duck.Quack() duck.Walk() } } type Bird struct { // ... } func (b *Bird) Quack() { fmt.Println("I am quacking!") } func (b *Bird) Walk() { fmt.Println("I am walking!") } func main() { b := new(Bird) DuckDance(b) }輸出:
I am quacking!
I am walking!
I am quacking!
I am walking!
I am quacking!
I am walking!
cannot use b (type *Bird) as type IDuck in function argument:
*Bird does not implement IDuck (missing Walk method)
type xmlWriter interface {
WriteXML(w io.Writer) error
}
// Exported XML streaming function.
func StreamXML(v interface{}, w io.Writer) error {
if xw, ok := v.(xmlWriter); ok {
// It’s an xmlWriter, use method of asserted type.
return xw.WriteXML(w)
}
// No implementation, so we have to use our own function (with perhaps reflection):
return encodeToXML(v, w)
}
// Internal XML encoding function.
func encodeToXML(v interface{}, w io.Writer) error {
// ...
}
//multi_interfaces_poly.go package main import "fmt" type Shaper interface { Area() float32 } type TopologicalGenus interface { Rank() int } type Square struct { side float32 } func (sq *Square) Area() float32 { return sq.side * sq.side } func (sq *Square) Rank() int { return 1 } type Rectangle struct { length, width float32 } func (r Rectangle) Area() float32 { return r.length * r.width } func (r Rectangle) Rank() int { return 2 } func main() { r := Rectangle{5, 3} // Area() of Rectangle needs a value q := &Square{5} // Area() of Square needs a pointer shapes := []Shaper{r, q} fmt.Println("Looping through shapes for area ...") for n, _ := range shapes { fmt.Println("Shape details: ", shapes[n]) fmt.Println("Area of this shape is: ", shapes[n].Area()) } topgen := []TopologicalGenus{r, q} fmt.Println("Looping through topgen for rank ...") for n, _ := range topgen { fmt.Println("Shape details: ", topgen[n]) fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank()) } }輸出:
Looping through shapes for area ...
Shape details: {5 3}
Area of this shape is: 15
Shape details: &{5}
Area of this shape is: 25
Looping through topgen for rank ...
Shape details: {5 3}
Topological Genus of this shape is: 2
Shape details: &{5}
Topological Genus of this shape is: 1
type Fooer interface {
Foo()
ImplementsFooer()
}
type Bar struct{}
func (b Bar) ImplementsFooer() {} func (b Bar) Foo() {}
fmt.Printf(format string, a ...interface{}) (n int, errno error)
這個函數通過列舉 slice 型別的實參動態確定所有引數的型別。並檢視每個型別是否實現了 String() 方法。
type Task struct {
Command string
*log.Logger
}
func NewTask(command string, logger *log.Logger) *Task {
return &Task{command, logger}
}
task.Log()
型別可以通過繼承多個介面來提供像 多重繼承一樣的特性:
type ReaderWriter struct {
*io.Reader
*io.Writer
}