golang 任何类型interface{}
2017-10-03 17:15
302 查看
golang中可以使用interface{}表示任何类型。
本文以例子的形式,演示interface{}的使用。
output:
$ ./test
int: 2
判断interface的类型,如果是int型,就输出接口表示的值。
有时,如果确定知道类型T(例如int),会直接使用如下方式进行断言:
但断言失败,会panic。可根据具体情况选择使用哪种方式。
如果t1为abc:
output:
$ ./test
string: abc
如果t1为23:
output:
$ ./test
int: 23
如果t1为1.2
output:
$ ./test
unknown type: 1.2
本文以例子的形式,演示interface{}的使用。
example1
package main import ( "fmt" ) func main() { var t1 interface{} = 2 v, ok := t1.(int) if ok { fmt.Println("int:", v) } else { fmt.Println("v:", v) } }
output:
$ ./test
int: 2
判断interface的类型,如果是int型,就输出接口表示的值。
有时,如果确定知道类型T(例如int),会直接使用如下方式进行断言:
v := t1.(int)
但断言失败,会panic。可根据具体情况选择使用哪种方式。
example2
package main import ( "fmt" ) func main() { var t1 interface{} = "abc" switch v := t1.(type) { case int: fmt.Println("int:", v) case string: fmt.Println("string:", v) default: fmt.Println("unknown type:", v) } }
如果t1为abc:
output:
$ ./test
string: abc
如果t1为23:
output:
$ ./test
int: 23
如果t1为1.2
output:
$ ./test
unknown type: 1.2
更多interface的参考
http://blog.csdn.net/lanyang123456/article/details/79354709相关文章推荐
- golang返回值为interface{}的类型判断
- golang返回值为interface{}的类型判断
- golang--从类型转换角度看interface
- golang Interface类型详解
- golang学习之Interface类型断言
- golang学习之interface与其它类型转换
- golang:interface{}类型测试
- golang--从类型转换角度看interface
- golang的interface到其他类型的数据转换
- Golang-interface(三 接口类型)
- 4000 golang返回值为interface{}的类型判断
- 【GoLang笔记】浅析Go语言Interface类型的语法行为及用法
- 工作随笔——Golang interface 转换成其他类型
- golang:interface{}类型测试
- C++ 指针(任何一个指针本身的类型都是unsigned long int型)
- Nothing是任何类型的子类这个定义非常好。
- Java中,既然double类型比float类型,表示的数值范围更大,大家都用double类型不就行了,Java还发明float类型干什么?因为占内存少于double,其他没有任何优势了
- golang类型系统笔记
- Golang 学习之路四:类型
- Golang 模拟java超类型(abstract class)的实现 推荐