动态类型断言Golang
我试图将接口动态转换回其原始结构,但在转换后访问结构的属性时遇到问题 以这段代码为例动态类型断言Golang,go,Go,我试图将接口动态转换回其原始结构,但在转换后访问结构的属性时遇到问题 以这段代码为例 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 mai
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中实现这一点。我看到一些帖子提到使用接口继承,但我的结构没有方法,所以我不确定如何使用接口
在go中是否可以这样做?代码中的函数structTest(val接口{})似乎是松散类型的。您向它传递一个非类型化参数,并期望它满足某些条件(将有字段A),它在任何类型化语言中看起来都很奇怪
在我看来,使用接口这种多态性可以表示为
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()
}
我希望能够将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)
}
为什么不从函数返回值呢。您的做法是正确的,只需返回值以获取结构,然后根据需要使用它。Go中没有继承(我不确定“使用接口的继承”是什么意思,因为接口实现了一种多态形式)。如果你在寻找继承,那么你是在试图用错误的工具解决问题。@Himanshu这是我试图做的一个简化示例。我想我可以抓取这些值并在地图或其他东西中返回它们。当我从每个结构中获取相同的内容时,这似乎是浪费,但我必须为每个开关选项复制粘贴它。@jhall1990如果不知道接口可以包含什么类型,然后使用开关进行检查,则无法检查接口的基础类型。因此,您可以使用map,key作为名称,value作为结构。这样,您就可以知道基于键的结构,并将其传递给函数。我似乎误解了你的问题,你能详细说明一下吗,这样我们才能更好地帮助你?