How Can I Read Integer Values in Go Without a For Loop?

Barbara Streisand
Release: 2024-10-30 05:30:28
Original
887 people have browsed it

How Can I Read Integer Values in Go Without a For Loop?

Efficiently Reading Integer Values in Golang

To read a set of integer values from standard input and store them in a slice without using a conventional for loop, an optimized approach can be employed.

Solution Using Recursive Function

This approach utilizes a recursive function, ReadN, which takes an integer slice, a starting index, and the number of integers to read. Through successive recursive calls, it efficiently assigns integers to the slice.

Sample Code:

<code class="go">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)
}</code>
Copy after login

Faster Input Scanning

For even faster input scanning, replace the custom Scan function with a more efficient alternative:

<code class="go">func Scan(a *int) (int, error) {
    return fmt.Scanf("%d\n", a)
}</code>
Copy after login

Sample Input and Output:

Enter the number of integers
3
Enter the integers
10 20 30
[10 20 30]
Copy after login

This optimized solution provides an efficient way to read integers from standard input, without the overhead of a for loop.

The above is the detailed content of How Can I Read Integer Values in Go Without a For Loop?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!