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

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

Calling function names from a slice and return a value

问题

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

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

  1. package main
  2. func A(x int) int {
  3. return x + 1
  4. }
  5. func B(x int) int {
  6. return x + 2
  7. }
  8. func C(x int) int {
  9. return x + 3
  10. }
  11. func main() {
  12. x := 10
  13. type fs func(x int) int
  14. f := []fs{A, B, C}
  15. fns := make([]func(), 3)
  16. for a, _ := range f {
  17. a := a
  18. fns[a] = func() {
  19. f[a](x)
  20. }
  21. }
  22. for _, f := range fns {
  23. f()
  24. }
  25. }

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:

  1. package main
  2. func A(x int) int {
  3. return x + 1
  4. }
  5. func B(x int) int {
  6. return x + 2
  7. }
  8. func C(x int) int {
  9. return x + 3
  10. }
  11. func main() {
  12. x := 10
  13. type fs func(x int) int
  14. f := []fs{A, B, C}
  15. fns := make([]func(), 3)
  16. for a, _ := range f {
  17. a := a
  18. fns[a] = func() {
  19. f[a](x)
  20. }
  21. }
  22. for _, f := range fns {
  23. f()
  24. }
  25. }

Go Playground

答案1

得分: 1

你叫它...

  1. for a, _ := range f {
  2. a := a
  3. fns[a] = func() {
  4. f[a](x) // 在这里
  5. }
  6. }

这是playground

英文:

You have call it...

  1. for a, _ := range f {
  2. a := a
  3. fns[a] = func() {
  4. f[a](x) // in this
  5. }
  6. }

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:

确定