Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make fmt.Scanln() read into a slice of integers

Tags:

go

I have a line containing 3 numbers that I want to read from stdin with fmt.Scanln() but this code won't work:

X := make([]int, 3)
fmt.Scanln(X...)
fmt.Printf("%v\n", X)

I get this error message:

cannot use X (type []int) as type []interface {} in function argument

I don't get it.

like image 839
Frolik Avatar asked Mar 14 '13 15:03

Frolik


People also ask

What is FMT Scanln?

The fmt. Scanln() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments. This function stops scanning at a newline and after the final item, there must be a newline or EOF.

How do you read an int in Golang?

Reading integer value from standard input in Golang is fairly simple with fmt. Scanf function.


1 Answers

Idiomatic Go would be:

func read(n int) ([]int, error) {
  in := make([]int, n)
  for i := range in {
    _, err := fmt.Scan(&in[i])
    if err != nil {
       return in[:i], err
    }
  }
  return in, nil
}

interface{} means nothing. Please don't use it if you don't have to.

like image 65
voutasaurus Avatar answered Oct 05 '22 10:10

voutasaurus