Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang built-in print(ln) function's weird behaviour

Faced some unexpected order of console output using built-in print(ln). Go version is 1.21.3.

The next code:

package main

import (
    "fmt"
)

func main() {
    println("a=1")
    a := 1
    fmt.Println(a)

    println("b=2")
    b := 2
    fmt.Println(b)

    a = b
    b = a
    fmt.Println(a)
    fmt.Println(b)
    println("ab")
}

has the next output on my local machine:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a=1
b=2
ab
1
2
2
2

Taking in account the actual order of calls, the expected output is:

a=1
1
b=2
2
2
2
ab

which satisfies my expectations when I use online Go compilers (including Go Playground).

It is also important that the order of print(ln) output (locally too) may vary extremely rarely but still wrong for the most part.

>Solution :

print writes to stderr, fmt.Print writes to stdout. You are observing two separate streams when you mix print and fmt.Print functions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading