Kedaar Rao
Kedaar Rao

Reputation: 127

Why does writer.Write(msg) fail to write to os.Stdout?

In the code bellow, why does the Write() operation not work?

package main

import (
    "fmt"
    "bufio"
    "os"
)

func main() {
    fmt.Println("Hello, playground")
    writer := bufio.NewWriter(os.Stdout)
    //var msg []byte
    msg := []byte{104, 101, 108, 108, 111, 10}
    _, err := writer.Write(msg)
    if err != nil {
        fmt.Println("some error")
    }
}

The output is:

Hello, playground

But it should be:

Hello, playground
hello

Also, I don’t want to use fmt.Println(). To be more specific, I get the data as []byte type

Upvotes: 0

Views: 813

Answers (1)

torek
torek

Reputation: 488123

As Cerise Limón noted in a comment, a writer.Write() call merely queues up more data to be written (depending on the buffer size and the amount of data). The actual write may happen later, or never. In your case, since you never tell the writer to finish any delayed write, no write ever happens.

You'll need to invoke writer.Flush() (not writer.WriterFlush(), that's a typo of sorts). This can return an error, if the write fails, so ideally you should check for that, not just defer the call and hope. However, there's not much you can do about the failure, if there is one.

You can do an explicit, in-line check for error, as I did here for instance, or you can just defer the flush call and throw away any error.

Upvotes: 2

Related Questions