go语言开发基础30 - 之go语言里的类型断言使用
空接口可以存储任意类型的值,那我们如何获取其存储的具体数据类型呢?
这里就用到了类型断言,具体示例如下:
类型断言示例一:
package main
import "fmt"
// 定义结构体
type Student struct {
Name string
Sex string
}
// Test函数,接受一个任意类型的变量(空接口支持任意类型的变量)
func Test(a interface{}) {
// 使用类型断言判断变量a是不是Student结构体类型的变量(有两个返回值,一个是变量的值,另一个是判断的结果,如果是Student类型的变量返回的是true,否则返回的是false)
b, ok := a.(Student)
// 判断类型断言的判断结果,如果不是Student类型的变量就打印错误信息
if ok ==false {
fmt.Println("convert failed")
return
}
// 如果是Student类型的变量就打印结果
fmt.Println(b) // 结果为:{Dream }
}
func main() {
var b Student
b.Name = "Dream"
Test(b)
}
类型断言示例二:
除了第一种类型断言的方法我们还可以使用switch进行类型断言,具体示例如下:
package main
import "fmt"
func just(items ...interface{}) {
for index, v := range items {
switch v.(type) {
case bool:
fmt.Printf("%d params is bool,value is %v\n",index, v)
case int, int32, int64:
fmt.Printf("%d params is int,value is %v\n",index, v)
case float32,float64:
fmt.Printf("%d params is float,value is %v\n",index, v)
case string:
fmt.Printf("%d params is string,value is %v\n",index, v)
case Student:
fmt.Printf("%d params is student,value is %v\n",index, v)
case *Student:
fmt.Printf("%d params is *student,value is %v\n",index, v)
case nil:
fmt.Printf("%d params is nil,value is %v\n",index, v)
default:
fmt.Println("type not fund")
}
}
}
func main() {
var b Student
b.Name = "Dream"
just(28,8.2,"str type",false,b,nil,&b)
}
// 执行结果为:
0 params is int,value is 28
1 params is float,value is 8.2
2 params is string,value is str type
3 params is bool,value is false
4 params is student,value is {Dream }
5 params is nil,value is <nil>
6 params is *student,value is &{Dream }
判断一个类型是否实现了指定的接口示例:
package main
import "fmt"
type File struct { // 定义file类型结构体
Name string
}
type ReadWriter interface { // ReadWriter接口里规定了Write和Read方法
Write()
Read()
}
// 给File类型实现Read和Write方法
func (self File) Read() {
fmt.Printf("read %s\n", self.Name)
}
func (self File) Write() {
fmt.Printf("write %s\n", self.Name)
}
func main() {
// 类型断言:判断一个变量是否实现了接口(实现了接口ok的值就是true、没实现ok的值就是false)
var f File // 定义File结构体类型的变量f
var b interface{} // 定义空接口类型的变量b
b = f // 将变量f赋值给b(这步一定要有,否则无法实现类型断言)
_, ok := b.(ReadWriter) // 判断File结构体类型的变量是否实现了ReadWriter接口
fmt.Println(ok) // 如果实现了ok的值是true、没有实现ok的值就是false
}

浙公网安备 33010602011771号