I am not sure what you want to be recursive. But as I understand your question as changing a for-loop into a recursion, I made it into a tail recursion in a closure, in a functional programing style.
func set(n int) {
a := make([]int, n)
var setRecursive func(int) // declare a function variable, which take an int as param.
setRecursive = func(i int) { // set the function in closure, so a and n is available to it.
if i == 0 { // end point of the recursion, return.
return
}
Scan(&a[n-i]) // Use fmt.Scan out of playground
setRecursive(i - 1) // tail recursion.
}
setRecursive(n) // call the function, start the recursion.
fmt.Println(a)
}
If you want the matter simpler, you can remove the closure part and move the line Scan(&a[n-i])
behind the line setRecursive(n)
, Like below:
func SetRecursive(a []int, n int) {
if n==0 {
return
}
SetRecursive(a,n-1) // recurse first, so we can scan in the right order.
Scan(&a[n-1])
}
Playground: https://play.golang.org/p/0io190tyviE