从切片中调用函数名并返回一个值

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

Calling function names from a slice and return a value

问题

我想调用存储在切片中的一系列函数名称。下面的代码片段目前可以工作,但我需要从这些函数中返回一个值。不幸的是,我不知道如何调用这些函数并存储返回值。有什么想法吗?

这是我目前正在处理的代码:

package main

func A(x int) int {
    return x + 1
}

func B(x int) int {
    return x + 2
}

func C(x int) int {
    return x + 3
}

func main() {
    x := 10
    type fs func(x int) int

    f := []fs{A, B, C}

    fns := make([]func(), 3)

    for a, _ := range f {
        a := a
        fns[a] = func() {
            f[a](x)
        }
    }

    for _, f := range fns {
        f()
    }
}

Go Playground

英文:

I want to call a number of function names stored in a slice. The code snippet below works so far but I need to return a value from those functions. Unfortunately I don't get it to work because I don't know to to call those functions and store the return value. Any ideas?

This is the code I'm currently working on:

package main

func A(x int) int {
    return x + 1
}

func B(x int) int {
    return x + 2
}

func C(x int) int {
    return x + 3
}

func main() {
    x := 10
    type fs func(x int) int

    f := []fs{A, B, C}

    fns := make([]func(), 3)

    for a, _ := range f {
	    a := a
	    fns[a] = func() {
		    f[a](x)
	    }
    }

    for _, f := range fns {
	    f()
    }

}

Go Playground

答案1

得分: 1

你叫它...

for a, _ := range f {
        a := a
        fns[a] = func() {
            f[a](x)        // 在这里
        }
    }

这是playground

英文:

You have call it...

for a, _ := range f {
        a := a
        fns[a] = func() {
            f[a](x)        // in this
        }
    }

here is the playground

huangapple
  • 本文由 发表于 2022年2月20日 07:04:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/71189950.html
匿名

发表评论

匿名网友

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

确定