如何选择要运行的随机函数?

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

How should a random function be chosen to be run?

问题

我有几个函数,想要随机选择一个来运行。我正在使用Go语言。

目前我正在使用switch语句。但是这种方式并不理想,因为如果我想要添加另一个函数,我必须增加rand.Intn()的范围,并添加一个新的case。而删除一个case则更糟糕,因为我还必须递减后面的所有case。

switch rand.Intn(5) {
case 0:
	function1()
case 1:
	function2()
case 2:
	function3()
case 3:
	function4()
case 4:
	function5()
}
英文:

I have several functions and want to choose one randomly to run. I am using Go.

Currently I am using a switch statement. This does not feel ideal because if I want to add another function I have to increment the rand.intn() and add a new case. Removing a case is even worse because then I also have to decrement all cases after that.

switch rand.Intn(5) {
case 0:
	function1()
case 1:
	function2()
case 2:
	function3()
case 3:
	function4()
case 4:
	function5()
}

答案1

得分: 2

使用一个函数数组或切片,将其长度作为 rand.Intn 的参数。

var funcs = [...]func() {
    function1,
    function2,
    // ...
}

func main() {
    funcs[rand.Intn(len(funcs))]()
}

点击此处查看示例代码

英文:

Use an array or slice of functions, use its length as the argument to rand.Intn.

var funcs = [...]func() {
    function1,
    function2,
    // ...
}

func main() {
    funcs[rand.Intn(len(funcs))]()
}

https://go.dev/play/p/62pjR4ogGqb

huangapple
  • 本文由 发表于 2023年3月25日 18:14:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75840982.html
匿名

发表评论

匿名网友

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

确定