加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Go语言-interface

发布时间:2020-12-16 18:17:52 所属栏目:大数据 来源:网络整理
导读:Go语言-interface 概念 Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。 代码 package mainimport "fmt"type Human struct {name stringage intphone string}type Student s

Go语言-interface

概念

Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。


代码
package main

import "fmt"

type Human struct {
	name  string
	age   int
	phone string
}
type Student struct {
	Human  //匿名字段
	school string
	loan   float32
}
type Employee struct {
	Human   //匿名字段
	company string
	money   float32
}

//Human实现Sayhi方法
func (h Human) SayHi() {
	fmt.Printf("Hi,I am %s you can call me on %sn",h.name,h.phone)
}

//Human实现Sing方法
func (h Human) Sing(lyrics string) {
	fmt.Println("La la la la...",lyrics)
}

//Employee重载Human的SayHi方法
func (e Employee) SayHi() {
	fmt.Printf("Hi,I am %s,I work at %s. Call me on %sn",e.name,e.company,e.phone) //Yes you can split into 2 lines here.
}

// Interface Men被Human,Student和Employee实现
// 因为这三个类型都实现了这两个方法
type Men interface {
	SayHi()
	Sing(lyrics string)
}

func main() {
	fmt.Println("-- -- --")
	
	mike := Student{Human{"Mike",25,"222-222-XXX"},"MIT",0.00}
	paul := Student{Human{"Paul",26,"111-222-XXX"},"Harvard",100}
	sam := Employee{Human{"Sam",36,"444-222-XXX"},"Golang Inc.",1000}
	Tom := Employee{Human{"Sam","Things Ltd.",5000}
	
	//定义Men类型的变量i
	var i Men
	
	//i能存储Student
	i = mike
	fmt.Println("This is Mike,a Student:")
	i.SayHi()
	i.Sing("November rain")
	fmt.Println("")
	
	//i也能存储Employee
	i = Tom
	fmt.Println("This is Tom,an Employee:")
	i.SayHi()
	i.Sing("Born to be wild")
	fmt.Println("")
	
	//定义了slice Men
	fmt.Println("Let's use a slice of Men and see what happens")
	x := make([]Men,3)
	//T这三个都是不同类型的元素,但是他们实现了interface同一个接口
	x[0],x[1],x[2] = paul,sam,mike
	for _,value := range x {
		value.SayHi()
	}
	fmt.Println("-- -- --")
}

运行:

D:2019hellotodaysrcmain1>go run go2.6.go -- -- -- This is Mike,a Student: Hi,I am Mike you can call me on 222-222-XXX La la la la... November rain This is Tom,an Employee: Hi,I am Sam,I work at Things Ltd.. Call me on 444-222-XXX La la la la... Born to be wild Let's use a slice of Men and see what happens Hi,I am Paul you can call me on 111-222-XXX Hi,I work at Golang Inc.. Call me on 444-222-XXX Hi,I am Mike you can call me on 222-222-XXX -- -- --

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读