Search code examples
windowsgostdoutstdin

How to print to console windows?


I want to run my go program from cmd like this:

 C:\go\awesomeProject> goprogramm.exe -generate -val=2

and want to get some feedback like this:

> Process started
> Something went wrong. Type e-mail to receive report:
> |...

Yeah, I googled a lot. Standard output, go exec'ing, pipes and etc. Just can't mix it up.


Solution

  • Simplest is to use the fmt package, and its global functions, e.g.:

    fmt.Println("Process started")
    fmt.Println("Something went wrong. Type e-mail to receive report:")
    
    var i int = 3
    var err error = io.Eof
    fmt.Printf("And some formatted text: number: %d, an error: %v\n", i, err)
    

    If you want more configuration or the option to redirect the output e.g. to a file (in the future), then you may use the log package.

    log.Println("Process started")
    log.Println("Something went wrong. Type e-mail to receive report:")
    
    var i int = 3
    var err error = io.Eof
    log.Printf("And some formatted text: number: %d, an error: %v", i, err)
    

    One notable difference is that by default the fmt package writes to os.Stdout, and the log package writes to os.Stderr. Both appear in your console, but should not be forgotten if you want to redirect those streams. Another difference is that the log package appends a newline to each call if it doesn't end with one.