当前位置:网站首页>【愚公系列】2022年08月 Go教学课程 036-类型断言
【愚公系列】2022年08月 Go教学课程 036-类型断言
2022-08-11 03:14:00 【愚公搬代码】
一、类型断言
1,类型断言的定义
GO中的类型断言用于检查接口类型变量所持有的值是否实现了期望的接口或者具体的类型。
类型断言的语法格式如下:
value, ok := x.(T)
其中,x 表示一个接口的类型的实际值,T 表示一个具体的类型(也可为接口类型)。
该断言表达式会返回 value(x的实际值)和ok(x的值是否等于T的类型),可根据该布尔值判断 x 是否为 T 类型:
- 如果 T 是具体某个类型,类型断言会检查 x 的动态类型是否等于具体类型 T。如果检查成功,类型断言返回的结果是 x 的动态值,其类型是 T。
- 如果 T 是接口类型,类型断言会检查 x 的动态类型是否满足 T。如果检查成功,x 的动态值不会被提取,返回值是一个类型为 T 的接口值。
- 无论 T 是什么类型,如果 x 是 nil 接口值,类型断言都会失败。
2.类型断言的使用
package main
import "fmt"
func main() {
var i interface{
}
i="abc"
value,ok:=i.(int)
if ok{
fmt.Println(value+10)
}else{
fmt.Println("类型推断错误")
}
}

3.案例
package main
import "fmt"
// 加法类
type Add struct {
Object
}
func (a *Add) GetResult() int {
// 方法的实现要和接口中方法的声明保持一致
return a.numA + a.numB
}
func (a *Add) SetData(data ...interface{
}) bool {
// 1: 对数据的个数进行校验。
var b bool = true
if len(data) > 2 {
fmt.Println("参数个数错误!!")
b = false
}
value, ok := data[0].(int)
if !ok {
fmt.Println("第一个数类型错误")
b = false
}
value1, ok1 := data[1].(int)
if !ok1 {
fmt.Println("第二个数据类型错误")
b = false
}
a.numA = value
a.numB = value1
// 2: 类型进行校验。
return b
}
// 减法类
type Sub struct {
Object
}
func (s *Sub) SetData(data ...interface{
}) bool {
// 1: 对数据的个数进行校验。
var b bool = true
if len(data) > 2 {
fmt.Println("参数个数错误!!")
b = false
}
value, ok := data[0].(int)
if !ok {
fmt.Println("第一个数类型错误")
b = false
}
value1, ok1 := data[1].(int)
if !ok1 {
fmt.Println("第二个数据类型错误")
b = false
}
s.numA = value
s.numB = value1
// 2: 类型进行校验。
return b
}
func (s *Sub) GetResult() int {
return s.numA - s.numB
}
type Object struct {
numA int
numB int
}
type Resulter interface {
GetResult() int
SetData(data ...interface{
}) bool // 完成参数运算的数据的类型校验。
}
// 对象问题
// 1: 定义一个新的类
type OperatorFactory struct {
}
// 2: 创建一个方法,在该方法中完成对象的创建
func (o *OperatorFactory) CreateOperator(op string) Resulter {
switch op {
case "+":
add := new(Add)
return add
case "-":
sub := new(Sub)
return sub
default:
return nil
}
}
func OperatorWho(h Resulter) int {
return h.GetResult()
}
func main() {
var operator OperatorFactory
obj := operator.CreateOperator("-")
b := obj.SetData(30, 10)
if b {
num := OperatorWho(obj)
fmt.Println(num)
}
}

边栏推荐
猜你喜欢
随机推荐
SQL 开发的十个高级概念
代码 Revert 后再次 Merge 会丢失的问题,已解决
(CVPR - 2017) in depth and potential body learning context awareness feature for pedestrian recognition
21 Day Learning Challenge Week 1 Summary
Summary of Logstash log data write exception troubleshooting
添加用户报错useradd: cannot open /etc/passwd
The practice of alibaba data synchronization component canal
电商项目——商城限时秒杀功能系统
UNI-APP_iphone苹果手机底部安全区域
Salesforce解散中国团队,什么样的CRM产品更适合中国人
CSAPP Data Lab
Add user error useradd: cannot open /etc/passwd
[BX]和loop
成都纸质发票再见!开住宿费电子发票即将全面取代酒店餐饮加油站发票
OpenCV创始人:开源绝不能完全免费!
[idea error] Invalid target distribution: 17 solution reference
DOM-DOM tree, a DOM tree has three types of nodes
2022-08-10 第六小组 瞒春 学习笔记
高度塌陷问题的解决办法
最倒霉与最幸运









