下面为大家带来go语言三种接口使用模式,代码基于go1.0.2版本
第一种:
package main import "fmt" type Writer interface { Write(data []byte) (int, error) } type writerImpl struct { } func (w *writerImpl) Write(data []byte) (int, error) { return len(data), nil } type Worker struct { Writer } func main() { worker := Worker{&writerImpl{}} // using by inteface n, err := worker.Write(nil) if err != nil { panic(err) } fmt.Println(n) }
package main import "fmt" type Writer interface { Write(data []byte) (int, error) } func New() Writer { return &writer{} } type writer struct { } func (w *writer) Write(data []byte) (int, error) { return len(data), nil } func main() { worker := New() // using by inteface n, err := worker.Write(nil) if err != nil { panic(err) } fmt.Println(n) }
第三种:
package main import "fmt" type Writer interface { Write(data []byte) (int, error) } func New() *writer { return &writer{} } type writer struct { } func (w *writer) Write(data []byte) (int, error) { return len(data), nil } func main() { worker := New() // using by inteface n, err := worker.Write(nil) if err != nil { panic(err) } fmt.Println(n) }
有疑问加站长微信联系(非本文作者)