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")
}
- 接口为非侵入性,实现不依赖于接口定义
- 接口的定义可以包含在接口使用者包内
- 即GoProgrammer在一个单独的包,使用的时候再定义接口Programmer,也是没问题的,因为是 Duck Type
接口变量
func TestInterfaceVar(t *testing.T) {
var programmer Programmer = &GoProgrammer{}
t.Logf("%T", programmer) // *interface_test.GoProgrammer
}
自定义类型
// 自定义类型(别名)
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))
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
A Guide to Monte Carlo Simulations in Statistical Physics
Landau, David P./ Binder, Kurt / Cambridge Univ Pr / 2005-9 / 786.00元
This new and updated edition deals with all aspects of Monte Carlo simulation of complex physical systems encountered in condensed-matter physics, statistical mechanics, and related fields. After brie......一起来看看 《A Guide to Monte Carlo Simulations in Statistical Physics》 这本书的介绍吧!