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
Release: 2024-12-17 09:37:25
Original
924 people have browsed it

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

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

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

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

Output:

[1 3 5 7 9] 5 <nil>
Copy after login

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!

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