Search code examples
functiongorandomswitch-statement

How should a random function be chosen to be run?


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()
}

Solution

  • 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