go interface 使用

  • 2022-07-09
  • 浏览 (931)

golang interface 使用样例

package main

/*
类型通过实现那些方法来实现接口。 没有显式声明的必要;所以也就没有关键字“implements“。

隐式接口解藕了实现接口的包和定义接口的包:互不依赖。

因此,也就无需在每一个实现上增加新的接口名称,这样同时也鼓励了明确的接口定义。
*/
import (
	"fmt"
	"strconv"
	"testing"
)

type Phone interface {
	call()
}

type Nokia struct {
}

type IPhone struct {
}

func (nokia Nokia) call() {
	fmt.Println("hi, nokia")
}

func (iphone IPhone) call() {
	fmt.Println("hi, iphone")
}

func TestInterface(t *testing.T) {
	var phone Phone
	phone = new(Nokia)
	phone.call()

	phone = new(IPhone)
	phone.call()
}

/*
一个普遍存在的接口是 fmt 包中定义的 Stringer。

type Stringer interface {
    String() string
}

Stringer 是一个可以用字符串描述自己的类型。`fmt`包 (还有许多其他包)使用这个来进行输出。
*/
type Person struct {
	Name string
	Age  int
}

func (p Person) String() string {
	return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}

func TestStringerInterface(t *testing.T) {
	a := Person{"Arthur Dent", 42}
	z := Person{"Zaphod Beeblebrox", 9001}
	fmt.Println(a, z)
}

/* IPAddr 类型实现 fmt.Stringer 以便用点分格式输出地址 */
type IPAddr [4]byte

func (ipAddr IPAddr) String() string {
	var s string
	for _, v := range ipAddr {
		s += strconv.Itoa(int(v)) + "."
	}
	s = s[0 : len(s)-1]
	return s
}

func TestIPToStr(t *testing.T) {
	addrs := map[string]IPAddr{
		"loopback":  {127, 0, 0, 1},
		"googleDNS": {8, 8, 8, 8},
		"nil":       {},
	}
	for n, a := range addrs {
		fmt.Printf("%v: %v\n", n, a)
	}
}

测试

执行测试代码 go test -v interface_test.go 可以查看执行结果

go test 使用请看:go test 使用

golang 使用样例汇总:go test

你可能感兴趣的文章

go array 使用

go defer 使用

go file 使用

go func 使用

go http 使用

go main 使用

go map 使用

go math 使用

go method 使用

go range 使用

0  赞