内容简介:在golang中,但是,当我们以这样的形式传入函数中,在进行处理时我们需要区分interface类型(因为即便传入的举个栗子:
在golang中, interface{}
允许接纳任意值,int, string, struct等,因此我可以很简单的将值传递到interface{},例如:
package main
import (
"fmt"
)
type User struct{
Name string
}
func main() {
any := 1
test(any)
any = "fidding"
test(any)
any := User{
Name: "fidding",
}
test(any)
}
// value 允许为任意值
func test(value interface{}) {
...
}
但是,当我们以这样的形式传入函数中,在进行处理时我们需要区分interface类型(因为即便传入的 User结构体
,interface本身也没有所谓的 Name
属性),此时就需要用到 type assertions
和 type switches
,来将其转换为我们需要的类型
举个栗子:
package main
import (
"fmt"
)
type User struct{
Name string
}
func main() {
any := User{
Name: "fidding",
}
test(any)
}
func test(value interface{}) {
switch v := value.(type) {
case string:
fmt.Println(v)
case int32, int64:
fmt.Println(v)
case User:
// 可以看到op即为将interface转为User struct类型,并使用其Name对象
op, ok := value.(User)
fmt.Println(op.Name, ok)
default:
fmt.Println("unknown")
}
}
执行输出结果为
fidding true
即我们可以对interface使用 .()
并在括号中传入想要解析的类型(如结构体),形如
// 如果转换失败ok=false,转换成功ok=true res, ok := anyInterface.(someType)
并且我们并不确定interface类型时候,也可以使用 anyInterface.(type)
结合 switch case
来做判断。
现在再回过头看上面的栗子,是不是更清楚了呢
happy coding!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- awk 将多行文件转为一行
- js 将线性数据转为树形
- 如何将 Canvas 绘制过程转为视频
- python中将list转为dict
- Unity Gamma校正转为线性空间
- MyBatis Map结果的Key转为驼峰式2
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Coding the Matrix
Philip N. Klein / Newtonian Press / 2013-7-26 / $35.00
An engaging introduction to vectors and matrices and the algorithms that operate on them, intended for the student who knows how to program. Mathematical concepts and computational problems are motiva......一起来看看 《Coding the Matrix》 这本书的介绍吧!