golang断言实践

package main

import "fmt"

type Usb interface {
	Start()
	Stop()
}

//手机
type Phone struct {
	Name string
}

//相机
type Camera struct {
	Name string
}

//计算机
type Computer struct {
}

//手机实现USB接口方法
func (p Phone) Start() {
	fmt.Println("手机开始工作...")
}
func (p Phone) Stop() {
	fmt.Println("手机停止工作...")
}
func (p Phone) Call() { //该方法未定义
	fmt.Println("我是手机,我要打电话...")
}

//相机实现USB接口方法
func (c Camera) Start() {
	fmt.Println("相机开始工作...")
}
func (c Camera) Stop() {
	fmt.Println("相机停止工作...")
}

//编写一个方法Working,接收一个USB接口类型变量
//实现了USB接口的所有方法
func (c Computer) Working(usb Usb) {
	//通过usb接口变量调用start和stop方法
	usb.Start()
	//如果USB是指向Phone结构体变量,还需要调用Call方法
	phone, ok := usb.(Phone)
	if ok {
		phone.Call()
	}
	usb.Stop()

}

func main() {

	var usbArr [3]Usb
	usbArr[0] = Phone{}
	usbArr[1] = Camera{}
	usbArr[2] = Phone{}

	//Phone还有一个特有的方法call(),请遍历Usb数组,如果是Phone变量,
	//除了调用Usb接口声明的方法外,还需要调用Phone特有方法Call(类型断言)
	var computer Computer
	for _, v := range usbArr {
		computer.Working(v)
	}
}

  

package main

import "fmt"

type student struct {
}

func TypeJudge(items ...interface{}) {
	for index, x := range items {
		switch x.(type) {
		case bool:
			fmt.Printf("第%v个参数是 bool 类型,值是%v\n", index, x)
		case float64, float32:
			fmt.Printf("第%v个参数是 float 类型,值是%v\n", index, x)
		case int, int32, int64:
			fmt.Printf("第%v个参数是 int 类型,值是%v\n", index, x)
		case string:
			fmt.Printf("第%v个参数是 string 类型,值是%v\n", index, x)
		case student:
			fmt.Printf("第%v个参数是 student 类型,值是%v\n", index, x)
		case *student:
			fmt.Printf("第%v个参数是 *student 类型,值是%v\n", index, x)
		default:
			fmt.Printf("第%v个参数是 %v 类型不确定", index, x)
		}
	}
}
func main() {

	var n1 float32 = 1.1
	var n2 float64 = 2.2
	var n3 int32 = 30
	var name string = "tom"
	address := "北京"
	n4 := 300
	stu := student{}
	stu1 := &student{}

	TypeJudge(n1, n2, n3, n4, name, address, stu, stu1)
}

  

posted @ 2022-03-10 20:32  Star_Gazer  阅读(70)  评论(0编辑  收藏  举报