go语言练习:接口

Posted ADChen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言练习:接口相关的知识,希望对你有一定的参考价值。

package main

import (
	"fmt"
)

type Run interface {              //这个接口的名字命名成Car更直观一点,除了distance方法外,后面可以加上百公里加速之类的方法
	distance() float64
    //celebrate() float64 } type Bwm struct { speed float64 name string t float64 } type Bens struct { speed float64 name string t float64 } func (bwm Bwm) distance() float64 { return bwm.speed*bwm.t } func (bens Bens) distance() float64 { return bens.speed*bens.t } func main() { x:=Bwm{100,"bwm",10} y:=Bens{120,"bens",10} fmt.Println(x.name,"has run:",Run.distance(x),"km in",x.t,"hours") fmt.Println(y.name,"has run:",Run.distance(y),"km in",y.t,"hours") }

  

以上是关于go语言练习:接口的主要内容,如果未能解决你的问题,请参考以下文章