我想實作一個像下面這樣的執行器:
type task func()
type executor struct {
tasks chan task
}
func (e *executor) Push(t task) {
select {
case e.tasks <- t:
default:
return
}
}
func (e *executor) Run() {
for {
select {
case t := <-e.tasks:
t()
}
}
}
func (e *executor) Init() {
e.tasks = make(chan task, 10)
}
然后,我想將任何函式包裝到任務型別中,就像這個偽代碼:
func make_task(f function_addr, args ...interface{}) task{
return func(){
f(args...)
}
}
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
你不能寫一個泛型函式來做你想做的事,但你可以使用閉包來做你需要的事情,比如:
executor.Push(func() {
someFunc(arg1,arg2,...)
})
其中arg1、arg2等是代碼中該點可用的引數。
uj5u.com熱心網友回復:
簡單的方法是使用函式文字代替 make_task:
t := func() { exampleFunction(exampleArg1, exampleArg2) }
e.Push(t)
如果由于某種原因簡單方法不適合您的應用程式,則使用反射包呼叫具有任意引數的任意函式:
func make_task(f interface{}, args ...interface{}) task {
return func() {
values := make([]reflect.Value, len(args))
for i := range args {
values[i] = reflect.ValueOf(args[i])
}
reflect.ValueOf(f).Call(values)
}
}
例子:
func hello(arg string) {
fmt.Println("Hello", arg)
}
…
t := make_task(hello, "world")
t() // prints Hello world
https://go.dev/play/p/5b6VPfV45qo
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369726.html
標籤:走
