Struct 让你的结构回到它';将数据类型作为接口传递并运行它';什么方法?
我有一个结构如下Struct 让你的结构回到它';将数据类型作为接口传递并运行它';什么方法?,struct,go,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
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
,该函数需要…接口{}
(因此任何类型都可以满足参数)
在函数fn
中,我想将我的structMyStruct
返回到它的数据类型和值,并运行它的方法get
,该方法也可以接受接收器,例如*http.Request
如何从接口arg[0]
获取我的结构,并使用传递指针的能力运行结构的方法get
。您需要的是。解决方案可以是这样的:
func fn(args ...interfaces) {
if strt, ok := args[0].(*MyStruct); ok {
// use struct
} else {
// something went wrong
}
// .......
}
听起来这里需要的是一个特定的接口,特别是一个具有
Get
方法的接口,该方法接受指向http.Request
的指针
例如:
type Getter interface {
Get(*http.Request)
}
func fn(getters ...Getter) {
getter := getters[0]
getter.Get(*http.Request)
}
func main() {
a := &MyStruct{}
fn(a)
}
这允许编译器检查
fn
的参数是否完全具有所需的方法,但它不需要知道有关该类型的任何其他信息。阅读有关接口的更多信息。请参阅:如果该结构是从另一个包传递的,而您不知道传递了哪个结构,该怎么办?Beego框架允许你传递你自己的结构,它是如何理解我们的方法的,并且把结构放在首位