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

DDD
Release: 2024-11-25 06:44:15
Original
927 people have browsed it

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

Parsing Numbers from Standard Input in Go

When working with multiple numeric inputs, Go allows developers to use multiple variables to capture individual values. However, what if you want to simplify this process and store all numbers in a single array or slice?

Consider the following code snippet:

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

This code efficiently reads two numbers and stores them in the numbers slice. However, if you have a large number of inputs, this approach can become verbose.

Can you read numbers directly into a slice using fmt.Fscan()?

Unfortunately, the fmt package does not natively support scanning into slices. To overcome this limitation, you can create a custom utility function to pack the addresses of all slice elements into an array of interfaces:

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 iterates through the slice, creating an array of pointers to each element.

Using the packAddrs() function to scan into a slice

With the packAddrs() function, you can now 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

The packAddrs() function converts the slice into an array of interfaces, allowing fmt.Fscan() to scan into each element.

Example using fmt.Sscan() for testing

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

In this example, I'm testing the code using fmt.Sscan(). It takes a string as input and returns the scanned values. The output of this code is:

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

This demonstrates how you can efficiently read multiple numbers into a slice by using the packAddrs() utility function.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template