Scanning Numbers into Arrays Using fmt.Fscan in Go
One of the tasks commonly encountered in programming is reading multiple numerical inputs from the user. In the Go language, this can be achieved using the fmt.Fscan function along with an array or slice to store the input values.
Consider the following code snippet, where the user is prompted to enter two numbers:
numbers := make([]int, 2) fmt.Fscan(os.Stdin, &numbers[0], &numbers[1])
By providing the memory addresses of individual array elements (numbers[0] and numbers[1]) as arguments to fmt.Fscan, we can efficiently read and store the input numbers in the array.
However, a more concise approach is desired, where we can directly scan the numbers into the array itself. To achieve this, we can create a utility function that creates a slice of pointers to the elements of our array:
func packAddrs(n []int) []interface{} { p := make([]interface{}, len(n)) for i := range n { p[i] = &n[i] } return p }
By passing the result of packAddrs to fmt.Fscan, we can effectively scan input numbers into the array:
numbers := make([]int, 2) n, err := fmt.Fscan(os.Stdin, packAddrs(numbers)...) fmt.Println(numbers, n, err)
This approach offers a simpler and more efficient way to read multiple numbers into an array using fmt.Fscan. It is particularly useful when the number of input values is not known in advance.
The above is the detailed content of How Can I Efficiently Scan Multiple Numbers into an Array Using Go\'s fmt.Fscan?. For more information, please follow other related articles on the PHP Chinese website!