Search code examples
goinput

Read line of numbers in Go


I have the following input, where on the first line is N - count of numbers, and on the second line N numbers, separated by space:

5
2 1 0 3 4

In Python I can read numbers without specifying its count (N):

_ = input()
numbers = list(map(int, input().split()))

How can I do the same in Go? Or I have to know exactly how many numbers are?


Solution

  • You can use this option:

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
    )
    
    func main() {
        reader := bufio.NewReader(os.Stdin)
        var n int
        fmt.Fscan(reader, &n)
        numbers := make([]int, n)
        for i := 0; i < n; i++ {
            fmt.Fscan(reader, &numbers[i])
        }
        fmt.Println(numbers)
    }