当前位置:网站首页>go接口变量的类型断言
go接口变量的类型断言
2022-07-25 17:36:00 【kankan231】
package main
import "fmt"
func main() {
var a interface{} = 1
//参与类型断言的变量必须是接口类型,否则编译错误
switch a.(type) {//a.(type)只能写在switch语句中,否则编译错误
case float32:
fmt.Println("变量是float类型")
case int://将匹配这个case
fmt.Println("变量是int类型")
default:
fmt.Println("变量是其它类型")
}
//写法一,安全断言
v1,ok:=a.(int)//断言成功
fmt.Printf("%v,%T,%v,%T",v1,v1,ok,ok)//输出 1,int,true,bool
v2,ok:=a.(*int)//断言失败
fmt.Printf("%v,%T,%v,%T",v2,v2,ok,ok)//输出 <nil>,*int,false,bool
//写法二,非安全断言
v3:=a.(int)//断言成功
fmt.Printf("%v,%T",v3,v3)//输出 1,int
v4:=a.(*int)//断言失败 panic: interface conversion: interface {} is main.User, not *main.User
fmt.Printf("%v,%T",v4,v4)
}
边栏推荐
- 第五章:流程控制
- 【Cadence Allegro PCB设计】error: Possible pin type conflict GND/VCC Power Connected to Output
- MySQL数据库中去重与连接查询的方法
- Tkinter module advanced operations (I) -- transparent buttons, transparent text boxes, custom buttons and custom text boxes
- 哈夫曼树的构建
- ACL 2022 | comparative learning based on optimal transmission to achieve interpretable semantic text similarity
- Technical difficulties and applications of large humanoid robots
- With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
- Random talk on generation diffusion model: DDPM = Bayesian + denoising
- 【无标题】
猜你喜欢

Stm32 paj7620u2 gesture recognition module (IIC communication) program source code explanation

"Digital security" alert NFT's seven Scams

Text translation software - text batch translation converter free of charge

I2C通信——时序图

Postdoctoral recruitment | West Lake University Machine Intelligence Laboratory recruitment postdoctoral / Assistant Researcher / scientific research assistant

Idea 必备插件

第六章 继承

Add batch delete

EasyUI modification and DataGrid dialog form control use

精彩记录
随机推荐
Chapter V: process control
Redis源码与设计剖析 -- 17.Redis事件处理
[vscode] support argparser/ accept command line parameters
Does PgSQL have a useful graphical management tool?
Installation steps and usage of NVM under windows10 system
11、照相机与透镜
EDI 对接CommerceHub OrderStream
第四章:操作符
Briefly describe the implementation principle of redis cluster
Solution for win10 device management not recognizing gtx1080ti display device
[knowledge atlas] practice -- Practice of question answering system based on medical knowledge atlas (Part3): rule-based problem classification
window10系统下nvm的安装步骤以及使用方法
[Hardware Engineer] Why do DC-DC isolated switching power modules use transformers?
PostgreSQL passwords are case sensitive. Is there parameter control?
更新|3DCAT实时云渲染 v2.1.2版本全新发布
第六章 继承
Jenkins' role based authorization strategy installation configuration
面试官:说说 log.Fatal 和 panic 的区别
03. Longest substring without repeated characters
Lvgl 7.11 tileview interface cycle switching