接口和多态、类型断言
[toc]
😶🌫️go语言官方编程指南:https://pkg.go.dev/std
go语言的官方文档学习笔记很全,推荐去官网学习
😶🌫️我的学习笔记:github: https://github.com/3293172751/golang-rearn
区块链技术(也称之为分布式账本技术),是一种互联网数据库技术,其特点是去中心化,公开透明,让每一个人均可参与的数据库记录
❤️💕💕关于区块链技术,可以关注我,共同学习更多的区块链技术。博客http://nsddd.top
接口体现多态
接口体现出多态
Golang数组中是什么类型的,那么其数据类型便是其数组的类型而不可以是其他的类型。
💡简单的一个案例如下:
package main
import (
	"fmt"
)
//声明/定义一个接口
type Usb interface {
	//声明了两个没有实现的方法
	Start()
	Stop()
}
type Phone struct {
	name string
}  
//让Phone 实现 Usb接口的方法
func (p Phone) Start() {
	fmt.Println("手机开始工作。。。")
}
func (p Phone) Stop() {
	fmt.Println("手机停止工作。。。")
}
type Camera struct {
	name string
}
//让Camera 实现   Usb接口的方法
func (c Camera) Start() {
	fmt.Println("相机开始工作。。。")
}
func (c Camera) Stop() {
	fmt.Println("相机停止工作。。。")
}
func main() {
	//定义一个Usb接口数组,可以存放Phone和Camera的结构体变量
	//这里就体现出多态数组
	var usbArr [3]Usb
	usbArr[0] = Phone{"vivo"}
	usbArr[1] = Phone{"小米"}
	usbArr[2] = Camera{"尼康"}
	
	fmt.Println(usbArr)
}
接口实现带参数方法
💡简单的一个案例如下:
/*
 * @Description: 接口带参数方法
 * @Author: xiongxinwei 3293172751nss@gmail.com
 * @Date: 2022-10-04 21:37:41
 * @LastEditTime: 2022-10-25 10:13:45
 * @FilePath: \code\go-super\30-main.go
 * @Github_Address: https://github.com/3293172751/cs-awesome-Block_Chain
 * Copyright (c) 2022 by xiongxinwei 3293172751nss@gmail.com, All Rights Reserved. @blog: http://nsddd.top
 */
package main
import "fmt"
type A interface {
	String() string
	//get和set方法
	GetName() string
	SetName(string)
}
type A1 struct {
	name string
	age  int64
}
func (a *A1) GetName() string {
	//可以是指针接收者,也可以是值接收者
	return a.name
}
func (a *A1) SetName(name string) {
	//必须是指针接收者
	a.name = name
}
func (a *A1) String() string {
	//打印结构体
	return fmt.Sprintf("name=%v age=%v", a.name, a.age)
}
func main() {
	//实现
	a1 := &A1{
		//必须是指针
		name: "Tom",
		age:  20,
	}
	var a A = a1
	fmt.Println(a)
	fmt.Println(a.GetName())
	a.SetName("Jack") //修改结构体的值
	fmt.Println(a.GetName())
	fmt.Println("a=", a)
}
🚀 编译结果如下:
[Running] go run "d:\文档\最近的\awesome-golang\docs\code\go-super\tempCodeRunnerFile.go"
name=Tom age=20
Tom
Jack
a= name=Jack age=20
结构体接收者和指针接收者实现接口区别
💡简单的一个案例如下:
/*
 * @Description: interface
 * @Author: xiongxinwei 3293172751nss@gmail.com
 * @Date: 2022-10-04 21:37:41
 * @LastEditTime: 2022-10-25 10:01:38
 * @FilePath: \code\go-super\29-main.go
 * @Github_Address: https://github.com/3293172751/cs-awesome-Block_Chain
 * Copyright (c) 2022 by xiongxinwei 3293172751nss@gmail.com, All Rights Reserved. @blog: http://nsddd.top
 */
package main
import "fmt"
type animal interface { //动物接口
	move()
	eat(string)
}
type cat struct { //猫结构体
	name string
	feet int8
}
func (c *cat) move() { //指针接收者实现接口
	fmt.Println("猫动")
}
func (c *cat) eat(food string) {
	fmt.Printf("猫吃%s\n", food)
}
func main() {
	var a = &cat{"tom", 4}
	//注意:接口变量保存的是一个指针,这个指针指向了实现该接口的自定义类型的变量(结构体变量)
	//var a = cat{"tom", 4} 错误写法
	var ai = a
	ai.move()
	ai.eat("fish")
}
🚀 编译结果如下:
猫动
猫吃fish
📜 对上面的解释:
接口变量保存的是一个指针,这个指针指向了实现该接口的自定义类型的变量(结构体变量)
var a = cat{"tom", 4}这个是错误写法
类型断言 – 接口判断类型
类型断言判断
💡简单的一个案例如下:
/*
 * @Description:类型断言 -- 接口类型转换
 * @Author: xiongxinwei 3293172751nss@gmail.com
 * @Date: 2022-10-04 21:37:41
 * @LastEditTime: 2022-10-25 09:26:03
 * @FilePath: \code\go-super\28-main.go
 * @Github_Address: https://github.com/3293172751/cs-awesome-Block_Chain
 * Copyright (c) 2022 by xiongxinwei 3293172751nss@gmail.com, All Rights Reserved. @blog: http://nsddd.top
 */
package main
import "fmt"
func main() {
	var a interface{}
	a = 10
	if v, ok := a.(float64); ok {
		fmt.Println("转换成功,a=", v)
	} else {
		fmt.Println("转换失败")
	}
	a = 10.4
	if v, ok := a.(float64); ok {
		fmt.Println("转换成功,a=", v)
	} else {
		fmt.Println("转换失败")
	}
}
🚀 编译结果如下:
[Running] go run "d:\文档\最近的\awesome-golang\docs\code\go-super\28-main.go"
转换失败
转换成功,a= 10.4
定义一个方法,可以传入任何类型的数据,就然后根据不同的类型,做不同的事情:
💡简单的一个案例如下:
注意: x.(type)只能结合switch使用
//if-else类型断言
func Prints(x interface{}) {
	if v, ok := x.(int); ok {
		fmt.Printf("x is a int, value is %v", v)
	} else if v, ok := x.(string); ok {
		fmt.Printf("x is a string, value is %v", v)
	} else {
		fmt.Println("unsupport type!")
	}
}
同样可以用switch实现:
//使用switch语句,可以判断一个变量是什么类型
func switch2(x interface{}) {
	switch x.(type) {
	case string:
		fmt.Println("x is a string")
	case int:
		fmt.Println("x is a int")
	case bool:
		fmt.Println("x is a bool")
	default:
		fmt.Println("unsupport type!")
	}
}
类型断言:如何检测和转换接口变量的类型
一个接口类型的变量 varI 中可以包含任何类型的值,必须有一种方式来检测它的 动态 类型,即运行时在变量中存储的值的实际类型。在执行过程中动态类型可能会有所不同,但是它总是可以分配给接口变量本身的类型。通常我们可以使用 类型断言 来测试在某个时刻 varI 是否包含类型 T 的值:
v := varI.(T)       // unchecked type assertion
varI 必须是一个接口变量,否则编译器会报错:invalid type assertion: varI.(T) (non-interface type (type of varI) on left) 。
类型断言可能是无效的,虽然编译器会尽力检查转换是否有效,但是它不可能预见所有的可能性。如果转换在程序运行时失败会导致错误发生。更安全的方式是使用以下形式来进行类型断言:
if v, ok := varI.(T); ok {  // checked type assertion
    Process(v)
    return
}
// varI is not of type T
如果转换合法,v 是 varI 转换到类型 T 的值,ok 会是 true;否则 v 是类型 T 的零值,ok 是 false,也没有运行时错误发生。
应该总是使用上面的方式来进行类型断言。
多数情况下,我们可能只是想在 if 中测试一下 ok 的值,此时使用以下的方法会是最方便的:
if _, ok := varI.(T); ok {
    // ...
}
示例 11.4 type_interfaces.go:
package main
import (
	"fmt"
	"math"
)
type Square struct {
	side float32
}
type Circle struct {
	radius float32
}
type Shaper interface {
	Area() float32
}
func main() {
	var areaIntf Shaper
	sq1 := new(Square)
	sq1.side = 5
	areaIntf = sq1
	// Is Square the type of areaIntf?
	if t, ok := areaIntf.(*Square); ok {
		fmt.Printf("The type of areaIntf is: %T\n", t)
	}
	if u, ok := areaIntf.(*Circle); ok {
		fmt.Printf("The type of areaIntf is: %T\n", u)
	} else {
		fmt.Println("areaIntf does not contain a variable of type Circle")
	}
}
func (sq *Square) Area() float32 {
	return sq.side * sq.side
}
func (ci *Circle) Area() float32 {
	return ci.radius * ci.radius * math.Pi
}
输出:
The type of areaIntf is: *main.Square
areaIntf does not contain a variable of type Circle
程序中定义了一个新类型 Circle,它也实现了 Shaper 接口。 if t, ok := areaIntf.(*Square); ok  测试 areaIntf 里是否有一个包含 *Square 类型的变量,结果是确定的;然后我们测试它是否包含一个 *Circle 类型的变量,结果是否定的。
备注
如果忽略 areaIntf.(*Square) 中的 * 号,会导致编译错误:impossible type assertion: Square does not implement Shaper (Area method has pointer receiver)。
类型判断:type-switch
接口变量的类型也可以使用一种特殊形式的 switch 来检测:type-switch (下面是示例 11.4 的第二部分):
switch t := areaIntf.(type) {
case *Square:
	fmt.Printf("Type Square %T with value %v\n", t, t)
case *Circle:
	fmt.Printf("Type Circle %T with value %v\n", t, t)
case nil:
	fmt.Printf("nil value: nothing to check?\n")
default:
	fmt.Printf("Unexpected type %T\n", t)
}
输出:
Type Square *main.Square with value &{5}
变量 t 得到了 areaIntf 的值和类型,所有 case 语句中列举的类型(nil 除外)都必须实现对应的接口(在上例中即 Shaper),如果被检测类型没有在 case 语句列举的类型中,就会执行 default 语句。
可以用 type-switch 进行运行时类型分析,但是在 type-switch 不允许有 fallthrough 。
如果仅仅是测试变量的类型,不用它的值,那么就可以不需要赋值语句,比如:
switch areaIntf.(type) {
case *Square:
	// TODO
case *Circle:
	// TODO
...
default:
	// TODO
}
下面的代码片段展示了一个类型分类函数,它有一个可变长度参数,可以是任意类型的数组,它会根据数组元素的实际类型执行不同的动作:
func classifier(items ...interface{}) {
	for i, x := range items {
		switch x.(type) {
		case bool:
			fmt.Printf("Param #%d is a bool\n", i)
		case float64:
			fmt.Printf("Param #%d is a float64\n", i)
		case int, int64:
			fmt.Printf("Param #%d is a int\n", i)
		case nil:
			fmt.Printf("Param #%d is a nil\n", i)
		case string:
			fmt.Printf("Param #%d is a string\n", i)
		default:
			fmt.Printf("Param #%d is unknown\n", i)
		}
	}
}
可以这样调用此方法:classifier(13, -14.3, "BELGIUM", complex(1, 2), nil, false) 。
在处理来自于外部的、类型未知的数据时,比如解析诸如 JSON 或 XML 编码的数据,类型测试和转换会非常有用。
测试一个值是否实现了某个接口
这是 11.3 类型断言中的一个特例:假定 v 是一个值,然后我们想测试它是否实现了 Stringer 接口,可以这样做:
type Stringer interface {
    String() string
}
if sv, ok := v.(Stringer); ok {
    fmt.Printf("v implements String(): %s\n", sv.String()) // note: sv, not v
}
Print 函数就是如此检测类型是否可以打印自身的。
接口是一种契约,实现类型必须满足它,它描述了类型的行为,规定类型可以做什么。接口彻底将类型能做什么,以及如何做分离开来,使得相同接口的变量在不同的时刻表现出不同的行为,这就是多态的本质。
编写参数是接口变量的函数,这使得它们更具有一般性。l
使用接口使代码更具有普适性。
标准库里到处都使用了这个原则,如果对接口概念没有良好的把握,是不可能理解它是如何构建的。
在接下来的章节中,我们会讨论两个重要的例子,试着去深入理解它们,这样你就可以更好的应用上面的原则。
接口嵌套
💡简单的一个案例如下:
/*
 * @Description:接口嵌套
 * @Author: xiongxinwei 3293172751nss@gmail.com
 * @Date: 2022-10-04 21:37:41
 * @LastEditTime: 2022-10-25 10:32:49
 * @FilePath: \code\go-super\31-main.go
 * @Github_Address: https://github.com/3293172751/cs-awesome-Block_Chain
 * Copyright (c) 2022 by xiongxinwei 3293172751nss@gmail.com, All Rights Reserved. @blog: http://nsddd.top
 */
package main
import "fmt"
type Ainterface interface {
	// A接口
	GetName() string
}
type Binterface interface {
	// B接口
	SetName(string)
}
type Animaler interface {
	// Animaler接口
	Ainterface
	Binterface
}
type Dog struct {
	// Dog
	name string
}
func (d *Dog) GetName() string {
	// 实现A接口
	return d.name
}
func (d *Dog) SetName(name string) {
	// 实现B接口
	d.name = name
}
func main() {
	dog := &Dog{
		name: "Tom",
	}
	var animaler Animaler = dog //animailer嵌套了Ainterface和Binterface
	fmt.Println(animaler.GetName())
	animaler.SetName("dog1")
	fmt.Println(animaler.GetName())
}
🚀 编译结果如下:
[Running] go run "d:\文档\最近的\awesome-golang\docs\code\go-super\31-main.go"
Tom
dog1
END 链接
✴️版权声明 © :本书所有内容遵循CC-BY-SA 3.0协议(署名-相同方式共享)©