首页 文章

动态类型断言Golang

提问于
浏览
0

我正在尝试将一个接口动态转换回它的原始结构,但是我在转换后访问结构的属性时遇到了问题 .

以此代码为例 .

package main

import (
    "fmt"
    "log"
)

type struct1 struct {
    A string
    B string
}

type struct2 struct {
    A string
    C string
}

type struct3 struct {
    A string
    D string
}

func main() {
    s1 := struct1{}
    s1.A = "A"
    structTest(s1)

    s2 := struct2{}
    s2.A = "A"
    structTest(s2)

    s3 := struct3{}
    s3.A = "A"
    structTest(s3)
}

func structTest(val interface{}) {
    var typedVal interface{}

    switch v := val.(type) {
    case struct1:
        fmt.Println("val is struct1")
    case struct2:
        fmt.Println("val is struct2")
    case struct3:
        fmt.Println("val is struct3")
    default:
        log.Panic("not sure what val is.")
    }

    fmt.Println(typedVal.A)
}

我希望能够将3种已知结构类型中的一种传递给我的函数 . 然后找出传入的结构类型以键入断言 . 最后,我希望能够访问类似的属性 .

基本上我想在我的结构中有一些基本的继承,但到目前为止似乎不可能在go中执行此操作 . 我看到一些帖子提到继承使用接口,但我的结构没有方法,所以我不知道如何使用接口 .

这样的事情可能吗?

2 回答

  • 0

    代码中的函数structTest(val interface {})似乎是松散类型的 . 你传递一个无类型的参数,并期望它满足某些条件(将有字段A),它在任何类型语言中看起来都很奇怪 .

    使用接口这种多态性,在Go中,在我看来,可以表达类似的东西

    package main
    
    import (
        "fmt"
        "log"
    )
    
    type A string
    type HasA interface {
        PrintA()
    }
    
    func (a A) PrintA() { fmt.Println(a) }
    
    type struct1 struct {
        A
        B string
    }
    
    type struct2 struct {
        A
        C string
    }
    
    type struct3 struct {
        A
        D string
    }
    
    func main() {
        s1 := struct1{}
        s1.A = "A"
        structTest(s1)
    
        s2 := struct2{}
        s2.A = "A"
        structTest(s2)
    
        s3 := struct3{}
        s3.A = "A"
        structTest(s3)
    }
    
    func structTest(val HasA) {
    
        switch val.(type) {
        case struct1:
            fmt.Println("val is struct1")
        case struct2:
            fmt.Println("val is struct2")
        case struct3:
            fmt.Println("val is struct3")
        default:
            log.Panic("not sure what val is.")
        }
    
        val.PrintA()
    }
    

    Playground

  • 0

    我希望能够将3种已知结构类型中的一种传递给我的函数 . 然后找出传入的结构类型以键入断言 . 最后,我希望能够访问类似的属性 .

    您可以使用类型断言来完成该操作 . 基本思路是,在类型切换的任何情况下,只需使用类型断言来获取相应类型的具体实例,然后您可以调用您希望的任何属性 .

    看一下下面的例子

    package main
    
    import (
        "fmt"
    )
    
    type test1 struct {
        A, B string
    }
    
    type test2 struct {
        A, C string
    }
    
    func testType(val interface{}) {
        switch val.(type) {
        case test1:
            t := val.(test1)
            fmt.Println(t.B)
            break
        case test2:
            t := val.(test2)
            fmt.Println(t.C)
            break
        }
    }
    
    func main() {
        t1, t2 := test1{B: "hello"}, test2{C: "world"}
        testType(t1)
        testType(t2)
    }
    

    Playground

相关问题