Home > Article > Backend Development > How Can I Read Integer Values in Go Without a For Loop?
Efficiently Reading Integer Values in Golang
To read a set of integer values from standard input and store them in a slice without using a conventional for loop, an optimized approach can be employed.
Solution Using Recursive Function
This approach utilizes a recursive function, ReadN, which takes an integer slice, a starting index, and the number of integers to read. Through successive recursive calls, it efficiently assigns integers to the slice.
Sample Code:
<code class="go">package main import "fmt" func main() { fmt.Println(`Enter the number of integers`) var n int if m, err := Scan(&n); m != 1 { panic(err) } fmt.Println(`Enter the integers`) all := make([]int, n) ReadN(all, 0, n) fmt.Println(all) } func ReadN(all []int, i, n int) { if n == 0 { return } if m, err := Scan(&all[i]); m != 1 { panic(err) } ReadN(all, i+1, n-1) } func Scan(a *int) (int, error) { return fmt.Scan(a) }</code>
Faster Input Scanning
For even faster input scanning, replace the custom Scan function with a more efficient alternative:
<code class="go">func Scan(a *int) (int, error) { return fmt.Scanf("%d\n", a) }</code>
Sample Input and Output:
Enter the number of integers 3 Enter the integers 10 20 30 [10 20 30]
This optimized solution provides an efficient way to read integers from standard input, without the overhead of a for loop.
The above is the detailed content of How Can I Read Integer Values in Go Without a For Loop?. For more information, please follow other related articles on the PHP Chinese website!