Reading numbers from os.Stdin into an array or fragment in Go

I can read several numbers using several variables, for example below.

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

Can I use numbers not as divided forms to simplify them?

numbers := make([]int, 2)
fmt.Fscan(os.Stdin, &numbers) // just an example, got error
+4
source share
1 answer

The package fmtdoes not process scanning fragments, but you can create a utility function that combines the addresses of all elements:

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

And using this, you can scan the entire fragment as follows:

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

Testing with fmt.Sscan():

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

Exit (try on Go Playground ):

[1 3 5 7 9] 5 <nil>
+2
source

Source: https://habr.com/ru/post/1694034/


All Articles