Home >Backend Development >Golang >How to Efficiently Read Multiple Numbers into a Go Slice from Standard Input?

How to Efficiently Read Multiple Numbers into a Go Slice from Standard Input?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 05:29:10110browse

How to Efficiently Read Multiple Numbers into a Go Slice from Standard Input?

Read Multiple Numbers into Go Slice from Standard Input

In Go, you can read multiple numbers into an array or slice using fmt.Fscan function. However, you may encounter an error when trying to scan directly into a slice. This is because the fmt.Fscan function does not inherently support scanning slices.

To solve this issue, you can create a utility function that packs the addresses of all the slice elements into an array. Here's how you would do it:

func packAddrs(n []int) []interface{} {
    p := make([]interface{}, len(n))
    for i := range n {
        p[i] = &n[i]
    }
    return p
}

Once you have the utility function, you can use it to scan a whole slice into an array:

numbers := make([]int, 2)
n, err := fmt.Fscan(os.Stdin, packAddrs(numbers)...)
fmt.Println(numbers, n, err)

For testing purposes, you can use fmt.Sscan to scan a string into the slice:

numbers := make([]int, 5)
n, err := fmt.Sscan("1 3 5 7 9", packAddrs(numbers)...)
fmt.Println(numbers, n, err)

Output (try it on the Go Playground):

[1 3 5 7 9] 5 <nil>

The above is the detailed content of How to Efficiently Read Multiple Numbers into a Go Slice from Standard Input?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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