Home >Backend Development >Golang >How to Efficiently Scan Multiple Numbers into a Slice in Go?

How to Efficiently Scan Multiple Numbers into a Slice in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 09:37:25925browse

How to Efficiently Scan Multiple Numbers into a Slice in Go?

Scanning Numbers into Slices in Go

When reading multiple numbers from standard input in Go, you can assign values to individual variables:

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

However, you may want to simplify the process and read directly into a slice. The fmt package doesn't support scanning into slices, but the following utility function can help:

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

This function creates a slice of addresses for each element in the input slice. With this function, you can scan into a slice like this:

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

Testing this with fmt.Sscan():

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>

The above is the detailed content of How to Efficiently Scan Multiple Numbers into a Slice in Go?. 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