http://blog.csdn.net/love_se/article/details/7947440
下面为大家带来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)
- }
注意,上面的 worker := Worker{&writerImpl{}} 很难理解,这里不是对一个类型取地址,而是用writerImpl生成一个
匿名对象,并对这个匿名对象取地址,writerImpl后面的{}是初始化时啥也没传
- 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)
- }
有疑问加站长微信联系(非本文作者)