Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we can stop bufio scanning at golang?

Tags:

go

buffer

What's the best way to stop the below scanning?

     outputReader := io.MultiReader(outReader, errReader)
     scanner := bufio.NewScanner(outputReader)
     for scanner.Scan(){
        scanner.Text():
     }   
like image 386
Mehrdad Avatar asked Sep 14 '25 16:09

Mehrdad


1 Answers

If you are stuck in continuous loop and hitting ENTER wont help in exiting the loop of scanner.Scan(), then try ctrl+Z to exit loop.

Below is an example code for taking input from console and printing the duplicate lines.

func main() {
    counts := make(map[string]int)
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Println("Accepting inputs")
    for scanner.Scan() {
        counts[input.Text()]++
    }
    // NOTE: ignoring potential errors from input.Err()
    fmt.Println("Printing output")
    for line, n := range counts {
        if n > 1 {
            fmt.Printf("Count: %d\t Line: %s\n", n, line)
        }
    }
}

Console Output:

Accepting inputs
Hi
hello
hi
Hi

^Z
Printing output
Count: 2         Line: Hi

We can see that just after pressing ctrl+Z the scanner.Scan() exited the loop.

like image 66
Gandharva S Murthy Avatar answered Sep 17 '25 08:09

Gandharva S Murthy