Go -- 接口

栏目: Go · 发布时间: 6年前

type Programmer interface {
    writeHelloWorld() string
}

// 不需要关键字:implements
type GoProgrammer struct {
}

// Duck Type式接口,与Programmer里面的方法签名完全一致
func (p *GoProgrammer) writeHelloWorld() string {
    return "fmt.Println(\"Hello World\")"
}

func TestInterface(t *testing.T) {
    var p Programmer
    p = new(GoProgrammer)
    t.Log(p.writeHelloWorld()) // fmt.Println("Hello World")
}
  1. 接口为非侵入性,实现不依赖于接口定义
  2. 接口的定义可以包含在接口使用者包内
    • 即GoProgrammer在一个单独的包,使用的时候再定义接口Programmer,也是没问题的,因为是 Duck Type

接口变量

func TestInterfaceVar(t *testing.T) {
    var programmer Programmer = &GoProgrammer{}
    t.Logf("%T", programmer) // *interface_test.GoProgrammer
}
Go -- 接口

自定义类型

// 自定义类型(别名)
type IntConvert func(op int) int

func timeSpent(inner IntConvert) IntConvert {
    return func(op int) int {
    	start := time.Now()
    	ret := inner(op)
    	fmt.Println("time spent : ", time.Since(start).Seconds())
    	return ret
    }
}

func slowFunc(op int) int {
    time.Sleep(time.Second * 1)
    return op
}

func TestFuncAsParam(t *testing.T) {
    f := timeSpent(slowFunc)
    t.Log(f(10))
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro CSS and HTML Design Patterns

Pro CSS and HTML Design Patterns

Michael Bowers / Apress / April 23, 2007 / $44.99

Design patterns have been used with great success in software programming. They improve productivity, creativity, and efficiency in web design and development, and they reduce code bloat and complexit......一起来看看 《Pro CSS and HTML Design Patterns》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具