案例:
package main
import(
"fmt"
)
//声明接口
type Usb interface{
//声明需要实现的方法
//方法名(参数列表)返回值列表
start()
stop()
}
//方法实现start 和 stop 方法
type Phone struct{
}
func (phone Phone) start(){
fmt.Println("手机连接开始。。。")
}
func (phone Phone) stop(){
fmt.Println("手机链接结束。。。")
}
func (phone Phone) call(){
fmt.Println("手机打电话。。。")
}
type Computer struct{
}
func (computer Computer) start(){
fmt.Println("电脑连接开始。。。")
}
func (computer Computer) stop(){
fmt.Println("电脑链接结束。。。")
}
//接口执行工作
type Working struct{
}
func (Working Working) GetWorking(usb Usb){
usb.start()
usb.stop()
//只要Phone 中有call方法,所以同时调用时,会出现Computer没有call方法
//所以此时需要使用 类型断言 来进行判断
//usb.(Phone) 类型断言
//phone , ok 是随意定义的
/*
if p , ok := usb.(Phone); ok {
p.call()
}
*/
if phone , ok := usb.(Phone); ok {
phone.call()
}
}
func main(){
working := Working{}
phone := Phone{}
computer := Computer{}
//方法以形参的方式传入GetWorking中
working.GetWorking(phone)
working.GetWorking(computer)
}
package main
import(
"fmt"
)
type Student struct{
}
func TypeJudge(items... interface{}){
for i,v := range items{
i += 1
switch v.(type) { //这里的type是一个关键字,固定写法
case bool:
fmt.Printf("param #%d is a bool 值是%v\n",i,v)
case float64:
fmt.Printf("param #%d is a float64 值是%v\n",i,v)
case int,int64:
fmt.Printf("param #%d is a int 值是%v\n",i,v)
case nil:
fmt.Printf("param #%d is a nil 值是%v\n",i,v)
case string:
fmt.Printf("param #%d is a string 值是%v\n",i,v)
case Student:
fmt.Printf("param #%d is a Student 值是%v\n",i,v)
case *Student:
fmt.Printf("param #%d is a *Student 值是%v\n",i,v)
default:
fmt.Printf("param #%d s type is unknown 值是%v\n",i,v)
}
}
}
func main(){
n1 := 10.1
n2 := 30
n3 := "aaaa"
n4 := true
n5 := 20.3
stu1 := Student{}
stu2 := &Student{}
TypeJudge(n1,n2,n3,n4,n5,stu1,stu2)
/*
param #1 is a float64 值是10.1
param #2 is a int 值是30
param #3 is a string 值是aaaa
param #4 is a bool 值是true
param #5 is a float64 值是20.3
param #6 is a Student 值是{}
param #7 is a *Student 值是&{}
*/
}