教程集 www.jiaochengji.com
教程集 >  脚本编程  >  C语言  >  正文 Golang中对interface{}做type assertion和type switch学习笔记

Golang中对interface{}做type assertion和type switch学习笔记

发布时间:2017-12-13   编辑:jiaochengji.com
教程集为您提供Golang中对interface{}做type assertion和type switch学习笔记等资源,欢迎您收藏本站,我们将为您提供最新的Golang中对interface{}做type assertion和type switch学习笔记资源
本文章来为各位介绍一篇关于Golang中对interface{}做type assertion和type switch学习笔记,希望文章对大家有帮助.

interface{}是一个通用类型,可以储存任意类型的值。如下方法来获取值的实际类型:
如果你比较确定类型可以使用type assertion:

var num interface{} = 100
if val,ok := num.(int); ok {
    fmt.Println(val)
}

如果你不确定interface{}的具体类型,使用type switch:

var str interface{} = "abc"
 
switch v := str.(type) {
case string:
 fmt.Println(v)
case int32, int64:
 fmt.Println(v)
default:
 fmt.Println("unknown")
}

您可能感兴趣的文章:
Golang中对interface{}做type assertion和type switch学习笔记
golang类型断言(Type Assertion)的应用
14. Go 语言中的类型断言是什么?
goLang 类型断言 type assertion
golang接口详解
Go语言interface详解
golang 初始化并赋值_Golang | 既是接口又是类型,interface是什么神仙用法?
使用Go语言一段时间的感受
go语言学习笔记 — 接口 — 接口与类型相互转换:在接口和类型之间转换
golang 反射机制

[关闭]
~ ~