struct - 在将它作为接口(interface)传递并运行它的方法后,让你将结构恢复为它的数据类型?

标签 struct go interface

我有一个结构如下

type MyStruct {
   EmbeddedFooBar
}

func (m *MyStruct) Foo(b *http.Request) {
   // Doing something
} 

func fn(args ...interfaces) {
    // It's here I want to get my struct back and run the "Get" method
    // Please keep in mind I am too pass a pointer param into the struct method
    strt := args[0]

    ....
    get struct back to static data type MyStruct
    and run "Get()", dont mind how/where I will get *http.Request to pass, assume I can
    ....

    strt.Get(*http.Request)
}

func main() {
    a := &MyStruct{}
    fn(a)
}

我将上面的结构传递给可变参数函数 fn,它需要 ...interfaces{}(因此任何类型都可以满足参数)

在函数 fn 中,我想将我的结构 MyStruct 取回它的数据类型和值,并运行它的方法 Get 也可以接受接收器,例如 *http.Request

如何从接口(interface) arg[0] 返回 My Struct 并运行具有传递指针能力的结构的方法 Get

最佳答案

你要的是Type Assertion .解决方案可能是这样的:

func fn(args ...interfaces) {
    if strt, ok := args[0].(*MyStruct); ok {
        // use struct
    } else {
        // something went wrong
    }
    // .......
}

关于struct - 在将它作为接口(interface)传递并运行它的方法后,让你将结构恢复为它的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31419128/

相关文章:

go - 有没有一种方法可以在多个处理程序中使用相同的request.Body,而无需手动编写大量代码,或者我需要更改执行此操作的方式?

docker - 使用Dockerfile执行两个命令

mysql - 使用 <cfloop> 从查询结果构建数组和数组数组

c - 这个双重类型定义会导致访问冲突吗?

c - 为结构体指针赋值的语法

c++ - 读取带分隔符的文件

go - 为什么 http.Get ("http://[::]:1234") 有效?

go - 如何在 Go 中迭代 []interface{}

java - onClick 从MainActivity 调用接口(interface)方法

java - 当 A 实现 B Java 时,ArrayList<A> 转换为 ArrayList<B>