Home > Backend Development > Golang > How Can I Efficiently Scan Multiple Numbers into an Array Using Go\'s fmt.Fscan?

How Can I Efficiently Scan Multiple Numbers into an Array Using Go\'s fmt.Fscan?

Patricia Arquette
Release: 2024-11-26 07:31:10
Original
683 people have browsed it

How Can I Efficiently Scan Multiple Numbers into an Array Using Go's fmt.Fscan?

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])
Copy after login

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
}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template