golang中的断言是什么意思?可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
Go语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(T),这里value就是变量的值,ok是一个bool类型,element是interface变量,T是断言的类型。
如果element里面确实存储了T类型的数值,那么ok返回true,否则返回false。
package main
import (
"fmt"
)
type Order struct {
ordId int
customerId int
callback func()
}
func main() {
var i interface{}
i = Order{
ordId: 456,
customerId: 56,
}
value, ok := i.(Order)
if !ok {
fmt.Println("It's not ok for type Order")
return
}
fmt.Println("The value is ", value)
}
输出:
The value is {456 56 <nil>}
常见的还有用switch来断言:
package main
import (
"fmt"
)
type Order struct {
ordId int
customerId int
callback func()
}
func main() {
var i interface{}
i = Order{
ordId: 456,
customerId: 56,
}
switch value := i.(type) {
case int:
fmt.Printf("It is an int and its value is %d\n", value)
case string:
fmt.Printf("It is a string and its value is %s\n", value)
case Order:
fmt.Printf("It is a Order and its value is %v\n", value)
default:
fmt.Println("It is of a different type")
}
}
输出:
It is a Order and its value is {456 56 <nil>}
golang的语言中提供了断言的功能。golang中的所有程序都实现了interface{}的接口,这意味着,所有的类型如string,int,int64甚至是自定义的struct类型都就此拥有了interface{}的接口,这种做法和java中的Object类型比较类似。那么在一个数据通过func funcName(interface{})的方式传进来的时候,也就意味着这个参数被自动的转为interface{}的类型。
如以下的代码:
func funcName(a interface{}) string {
return string(a)
}
编译器将会返回:
cannot convert a (type interface{}) to type string: need type assertion
此时,意味着整个转化的过程需要类型断言。类型断言有以下几种形式:
直接断言使用
var a interface{}
fmt.Println("Where are you,Jonny?", a.(string))
但是如果断言失败一般会导致panic的发生。所以为了防止panic的发生,我们需要在断言前进行一定的判断。
value, ok := a.(string)
如果断言失败,那么ok的值将会是false,但是如果断言成功ok的值将会是true,同时value将会得到所期待的正确的值。示例:
value, ok := a.(string)
if !ok {
fmt.Println("It's not ok for type string")
return
}
fmt.Println("The value is ", value)
另外也可以配合switch语句进行判断:
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
另外补充几个go语言编程的小tips:
(1)如果不符合要求可以尽快的return(return as fast as you can),而减少else语句的使用,这样可以更加直观一些。
(2)转换类型的时候如果是string可以不用断言,使用fmt.Sprint()函数可以达到想要的效果。
(3)变量的定义和申明可以用组的方式,如:
var (
a string
b int
c int64
...
)
import (
"fmt"
"strings"
"net/http"
...
)
(4)函数逻辑比较复杂,可以把一些逻辑封装成一个函数,提高可读性。
(5)使用net/http包和net/url包的函数,可能会带有url encode功能,需要注意。
看完上述内容,你们对golang中的断言有进一步的了解吗?如果还想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。