Home >Backend Development >Golang >How Can I Efficiently Read Multiple Numbers into a Go Slice Using fmt.Fscan?

How Can I Efficiently Read Multiple Numbers into a Go Slice Using fmt.Fscan?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 21:53:15682browse

How Can I Efficiently Read Multiple Numbers into a Go Slice Using fmt.Fscan?

Reading Numbers into Slices Using fmt.Fscan

To read multiple numbers into an array or slice in Go using fmt.Fscan, it is common practice to declare individual variables and provide their addresses as arguments:

numbers := make([]int, 2)
fmt.Fscan(os.Stdin, &numbers[0], &numbers[1])

However, it is not possible to directly pass the slice itself as a parameter to fmt.Fscan. To simplify this process, you can create a utility function that packs the addresses of the slice elements:

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

Using this function, you can now scan a whole slice with fmt.Fscan:

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

For example, consider the following test input:

1 3 5 7 9

Using fmt.Sscan for testing purposes:

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

This demonstrates how to efficiently read multiple numbers into a slice using fmt.Fscan.

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!

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