Home >Backend Development >Golang >How Can I Efficiently Read Multiple Numbers into a Go Slice Using `fmt.Fscan()`?
Parsing Numbers from Standard Input in Go
When working with multiple numeric inputs, Go allows developers to use multiple variables to capture individual values. However, what if you want to simplify this process and store all numbers in a single array or slice?
Consider the following code snippet:
numbers := make([]int, 2) fmt.Fscan(os.Stdin, &numbers[0], &numbers[1])
This code efficiently reads two numbers and stores them in the numbers slice. However, if you have a large number of inputs, this approach can become verbose.
Can you read numbers directly into a slice using fmt.Fscan()?
Unfortunately, the fmt package does not natively support scanning into slices. To overcome this limitation, you can create a custom utility function to pack the addresses of all slice elements into an array of interfaces:
func packAddrs(n []int) []interface{} { p := make([]interface{}, len(n)) for i := range n { p[i] = &n[i] } return p }
This function iterates through the slice, creating an array of pointers to each element.
Using the packAddrs() function to scan into a slice
With the packAddrs() function, you can now scan into a slice like this:
numbers := make([]int, 2) n, err := fmt.Fscan(os.Stdin, packAddrs(numbers)...) fmt.Println(numbers, n, err)
The packAddrs() function converts the slice into an array of interfaces, allowing fmt.Fscan() to scan into each element.
Example using fmt.Sscan() for testing
numbers := make([]int, 5) n, err := fmt.Sscan("1 3 5 7 9", packAddrs(numbers)...) fmt.Println(numbers, n, err)
In this example, I'm testing the code using fmt.Sscan(). It takes a string as input and returns the scanned values. The output of this code is:
[1 3 5 7 9] 5 <nil>
This demonstrates how you can efficiently read multiple numbers into a slice by using the packAddrs() utility function.
The above is the detailed content of How Can I Efficiently Read Multiple Numbers into a Go Slice Using `fmt.Fscan()`?. For more information, please follow other related articles on the PHP Chinese website!