教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 4.9 go空接口及断言

4.9 go空接口及断言

发布时间:2022-01-11   编辑:jiaochengji.com
教程集为您提供4.9 go空接口及断言等资源,欢迎您收藏本站,我们将为您提供最新的4.9 go空接口及断言资源
<pre><code class="language-Go">package main import "fmt" /** 01 空接口不包含任何方法,正因为如此所有的类型都实现了空接口 因此空接口可以存储任意类型的数值 var v1 interface{}=1 var v2 interface{}="abc" var v3 interface{}=&v2 **/ type Student struct { name string age int } func main() { var v4 interface{} = struct{ x int }{1} fmt.Println("v4=", v4) //02空接口的应用 func Printlf(fmt string, args...interface{}) // func Println(args...interface{}) //03判断空接口参数 i := make([]interface{}, 3) i[0] = 1 i[1] = "hi" i[2] = Student{"huahu", 33} //类型查询,类型断言;确定类型后才能给其他变量赋值,不能强转!!! for index, data := range i { if value, ok := data.(int); ok == true { fmt.Printf("x[%d]类型为int,内容为%d\n", index, value) } else if value, ok := data.(string); ok == true { fmt.Printf("x[%d]类型为string,内容为%s\n", index, value) } else if value, ok := data.(Student); ok == true { fmt.Printf("x[%d],内容为%v\n", index, value) } } for index, data := range i { switch value := data.(type) { case int: fmt.Printf("x[%d]类型为int,内容为%d\n", index, value) case string: fmt.Printf("x[%d]类型为string,内容为%s\n", index, value) case Student: fmt.Printf("x[%d],内容为%v\n", index, value) } } } </code></pre>

 

到此这篇关于“4.9 go空接口及断言”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
4.9 go空接口及断言
初识 go 语言:方法,接口及并发
Go语言基础之接口(面向对象编程下)
go struct 成员变量后面再加个字符串是什么意思?_Go语言的学习笔记(第十章) 接口...
2020-10-18Go语言接口
Go语言接口interface
Go语言的空接口,接口类型断言
第07章 Go语言接口(interface),Golang接口(interface)
go 获取函数地址_Go语言基础--接口浅析
基于类型系统的面向对象编程语言Go

[关闭]
~ ~