Go语言 在struct中使用参数按名称定义函数

ih99xse1  于 2023-02-27  发布在  Go
关注(0)|答案(1)|浏览(124)

我想生成一个带不同参数的函数切片,传递给一个通道,在从通道阅读后运行。是否可以通过名称定义函数,并在结构体中指定参数,以便稍后调用?
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)
}
w8rqjzmb

w8rqjzmb1#

将函数和参数打包到闭包中。

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

相关问题