5

I want to read a set of integer values from stdin and put it into integer slice. What is the fastest way to do that without using for loop.

e.g.

Enter the number of integers
3
Enter the integers
23 45 66

How can I put these values in an integer slice?

kosta
  • 4,302
  • 10
  • 50
  • 104

2 Answers2

7

Anyway there is a loop, Here without for and goto loop ( try it on The Go Playground):

package main

import "fmt"

func main() {
    fmt.Println(`Enter the number of integers`)
    var n int
    if m, err := Scan(&n); m != 1 {
        panic(err)
    }
    fmt.Println(`Enter the integers`)
    all := make([]int, n)
    ReadN(all, 0, n)
    fmt.Println(all)
}

func ReadN(all []int, i, n int) {
    if n == 0 {
        return
    }
    if m, err := Scan(&all[i]); m != 1 {
        panic(err)
    }
    ReadN(all, i+1, n-1)
}

func Scan(a *int) (int, error) {
    return fmt.Scan(a)
}

io:

Enter the number of integers
3
Enter the integers
10 20 30
[10 20 30]

For faster input scanning rewrite:

func Scan(a *int) (int, error) {
    return fmt.Scan(a)
}

using:
Faster input scanning

Community
  • 1
  • 1
4

Simpler solution using loop without the need for using recursion function:

    var n int

    if _, err := fmt.Scan(&n); err != nil {
        panic(err)
    }

    arr := make([]int, n)

    for i := 0;i<n;i++{

        if _, err := fmt.Scan(&arr[i]); err != nil {
            panic(err)
        }
    }

    fmt.Println(arr)
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75