我有一个结构如下
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/