go语言接口使用

下面为大家带来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)
}

你可能感兴趣的:(golang,go语言,go语言编程,go语言接口使用,golang,interface,go,interface)