英文:
Defining function by name with arguments in struct
问题
我想生成一系列具有不同参数的函数片段,以便在从通道读取后传递给通道并运行。是否可以通过名称定义函数,并在稍后调用时在结构体中指定参数?
package main
import (
"context"
"fmt"
)
type ExecutionFn func(ctx context.Context, args interface{}) (interface{}, error)
type Job struct {
Name string
ExecFn ExecutionFn
Args interface{}
}
func (j Job) execute(ctx context.Context) (interface{}, error) {
fmt.Printf("Running job: %s\n", j.Name)
return j.ExecFn(ctx, j.Args)
}
func someFunction(description string, i int) (int, error) {
fmt.Println(description)
return i * 2, nil
}
func main() {
ctx := context.TODO()
i := 1
job := Job{
Name: fmt.Sprintf("Job %d", i),
ExecFn: someFunction,
Args: "Multiply by two", i, // 要传递给"someFunction"的参数值
}
fmt.Printf("%#v\n", job)
result, err := job.execute(ctx)
if err != nil {
panic(err)
}
fmt.Printf("Result: %v", result)
}
链接:https://go.dev/play/p/G9I7JEbA-Ol
英文:
I want to generate a slice of functions with different arguments to pass to a channel to be run after reading from the channel. Is it possible to define the function by name and specify the arguments in the struct to be called later?
https://go.dev/play/p/G9I7JEbA-Ol
package main
import (
"context"
"fmt"
)
type ExecutionFn func(ctx context.Context, args interface{}) (interface{}, error)
type Job struct {
Name string
ExecFn ExecutionFn
Args interface{}
}
func (j Job) execute(ctx context.Context) (interface{}, error) {
fmt.Printf("Running job: %s\n", j.Name)
return j.ExecFn(ctx, j.Args)
}
func someFunction(description string, i int) (int, error) {
fmt.Println(description)
return i * 2, nil
}
func main() {
ctx := context.TODO()
i := 1
job := Job{
Name: fmt.Sprintf("Job %d", i),
ExecFn: someFunction,
Args: "Multiply by two", i, // the values of the args to go to "someFunction"
}
fmt.Printf("%#v\n", job)
result, err := job.execute(ctx)
if err != nil {
panic(err)
}
fmt.Printf("Result: %v", result)
}
答案1
得分: 4
将函数和参数封装在闭包中。
type Job struct {
Name string
ExecFn func()
}
...
job := Job{
Name: fmt.Sprintf("Job %d", i),
ExecFn: func() { someFunction("Multiply by two", i) }
}
...
j.ExecFn() // 调用函数
英文:
Package the function and arguments in a closure.
type Job struct {
Name string
ExecFn func()
}
...
job := Job{
Name: fmt.Sprintf("Job %d", i),
ExecFn: func() { someFunction("Multiply by two", i) }
}
...
j.ExecFn() // invoke the function
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论