Golang中的自定义类型之间的转换的实现(type conversion)
这里不讨论数值与字符串之间、或者整型与浮点型之间的转换。这里要讨论的是自定义类型之间的转换,这个转换与其他语言都不一样,而且在go的源码中也被大量使用。
这里列举两个实用的例子。
转换成实现了某个(些)接口的自定义类型
比如:sort包里面的IntSlice,是一个[]int的自定义类型,并且实现了sort.Interface接口,如下所示:
typeIntSlice[]int //实现sort.Interface接口的方法 func(pIntSlice)Len()int{returnlen(p)} func(pIntSlice)Less(i,jint)bool{returnp[i]
当我们需要对一个int切片进行排序的时候,我们就可以直接把[]int]转换成sort.IntSlice,然后直接调用Sort()方法。
ints:=[]int{1,7,2,3,8,0} sort.IntSlice(ints).Sort()将函数转换成实现了某个(些)接口的函数
典型的一个案例就是http.HandlerFunc,通过这个类型,可以使得一个普通函数成为一个Http处理器(handler)。
typeHandlerFuncfunc(ResponseWriter,*Request) //实现http.Handler接口的方法 func(fHandlerFunc)ServeHTTP(wResponseWriter,r*Request){ f(w,r) }只要某个函数f具有跟HandlerFunc一样的函数签名(signature),那么这个函数就可以被转换成http.HandlerFunc。而
http.HandlerFunc又实现了http.Handler接口,那么这个函数f就可以被http服务器调用了。 funcf(wResponseWriter,r*Request){ //... } http.Handle("/args",http.HandlerFunc(f))在Golang中,这种用法很普遍,可以使用更少的代码实现与其他语言一样的功能。
到此这篇关于Golang中的自定义类型之间的转换的实现(typeconversion)的文章就介绍到这了,更多相关Golang自定义类型转换内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。