在结构体中按名称定义带参数的函数。

huangapple go评论74阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月21日 00:08:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75511648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定