当前位置:网站首页>Golang 类型断言
Golang 类型断言
2022-06-23 22:12:00 【别抢我的辣条~】
一,如何检测和转换接口变量的类型
在Go语言的interface中可以是任何类型,所以Go给出了类型断言来判断某一时刻接口中所含有的类型,例如现在给出一个接口,名为InterfaceText:
x,err:=interfaceText.(T)//T是某一种类型
上式是接口断言的一般形式,因为此方法不一定每次都可以完好运行,所以err的作用就是判断是否出错。所以一般接口断言常用以下写法:
if v,err:=InterfaceText.(T);err {//T是一种类型
possess(v)//处理v
return
}如果转换合法,则v为InterfaceText转换为类型T的值,err为ture,反之err为false。
值得注意的是:InterfaceText必须是接口类型!!!
有些时候若是想仅判断是否含有类型T,可以写为:
if _,err:=InterfaceText.(T);err{
//..
return
}下面给出一个具体的例子帮助理解:
package main
import (
"fmt"
"math"
)
type Square struct{
slide float32
}
type Circle struct{
radius float32
}
type Figure interface{
Area() float32
}
func main(){
var fi Figure
sq:=new(Square)
sq.slide=5
fi=sq
if v,err:=fi.(*Square);err {
fmt.Printf("fi contain a variable of type : %v\n",v)
}else {
fmt.Println("fi does not contain a variable of Square")
}
if v2,ok:=fi.(*Circle);ok {
fmt.Printf("fi contain a variable of type : %v\n",v2)
}else {
fmt.Println("fi does not contain a variable of Circle")
}
}
func (s *Square) Area() float32{
return s.slide*s.slide
}
func (c *Circle) Area() float32{
return c.radius*c.radius*math.Pi
}运行结果:

二,类型判断:type-switch
这是另一种类型判断的方法,此方法和switch很相似。直接看代码:
switch x:=InterfaceText.(type) {
case *Square:
fmt.Printf("text:%v",i)
case *Circle:
//..
case nil:
//..
default:
//..
//..and so forth
}理解思路和switch很相似,如果InterfaceText中有*Square,*Circle,nil三种类型,就会执行对应的代码,若都没有,便会执行default里的代码。
如果仅判断,而不使用值的话可以写为:
switch InterfaceText.(type) {
case *Square:
fmt.Printf("text:%v",i)
case *Circle:
//..
case nil:
//..
default:
//..
//..and so forth
}有时为了方便,我们可以把它打包成一个函数来判断一些未知类型:
func classify(items...interface{}){
for i,x:=range items {
switch x.(type) {
case bool:
fmt.Printf("text:%v",i)
case int:
//..
case float32:
//..
default:
//..
//..and so forth
}
}
}可以这样调用此方法:classifier(13, -14.3, false) 。
当然也可以加入其他类型,这个看具体情况而定。
ending~~
边栏推荐
- How to index websites in Google
- C# Winform 自定义进度条ProgressBar
- 云原生流水线工具汇总
- How can wechat video numbers be broadcast live on a PC?
- kubernetes之常用核心资源对象
- PHP的curl功能扩展基本用法
- Summary of some indicators for evaluating and selecting the best learning model
- The fortress machine installs pytorch, mmcv, and mmclassification, and trains its own data sets
- MySQL transaction isolation
- 短视频挺进在线音乐腹地
猜你喜欢

Ambire 指南:Arbitrum 奥德赛活动开始!第一周——跨链桥
Summary of cloud native pipeline tools

短视频挺进在线音乐腹地
Trigger definition and syntax introduction in MySQL

Million message IM system technical points sharing

Kotlin coroutine asynchronous flow
Androidkotlin comprehensive and detailed class usage grammar learning guide

Summary of some indicators for evaluating and selecting the best learning model
![[observation] Dell technology + Intel aoteng Technology: leading storage innovation with](/img/cf/3e3eb6389693667edad534b556c15c.png)
[observation] Dell technology + Intel aoteng Technology: leading storage innovation with "nanosecond speed"

Telecommuting: how to become a master of time management| Community essay solicitation
随机推荐
Bilibili×蓝桥云课|线上编程实战赛全新上新!
嵌入式接口之TIM定时器与NVIC的STM32模板库函数的一些解释
Analysis of Alibaba cloud Tianchi competition -- prediction of o2o coupon
Fabric.js 手动加粗文本iText
Is the geTx status management in the flutter really so good to use?
Trigger definition and syntax introduction in MySQL
Which securities dealers recommend? Is online account opening safe?
Practice of issuing vouchers for Tiktok payment of 100000 TPS traffic
不同网络结构的特征也能进行对比学习?蚂蚁&美团&南大&阿里提出跨架构自监督视频表示学习方法CACL,性能SOTA!...
C#/VB. Net word to text
【观察】戴尔科技+英特尔傲腾技术:以“纳秒之速”领跑存储创新
Bitmap加载内存分析
PyQt5_QTableWidget分页单选右键菜单控件
The fortress machine installs pytorch, mmcv, and mmclassification, and trains its own data sets
Sorry, your USB cable may be wrong!
PHP curl function extension basic usage
How does the fortress connection key server associate with the server host?
网站如何在Google建立索引
Aicon2021 | AI technology helps content security and promotes the healthy development of Internet Environment
Postman可以集成到CI,CD流水线中做自动化接口测试吗?