golang如何将interface转为struct结构体

栏目: Go · 发布时间: 6年前

内容简介:在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 assertionstype 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!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Coding the Matrix

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》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具