DEV Community

Lane Wagner
Lane Wagner

Posted on • Originally published at qvault.io on

Unexpected Printf Behavior in Go WASM – Nothing Prints

fmt.Printf doesn't do what you think it does WASM Go

The post Unexpected Printf Behavior in Go WASM – Nothing Prints appeared first on Qvault.

While working on Qvault’s Go Playground, I came across a very strange error. The standard library’s fmt.Printf() function prints nothing to the console when called. Nothing.

For those of you who are familiar with the function, when compiled to a “normal” executable fmt.Printf prints a formatted string to standard output. As per the official documentation, this program:

package main

import (
    "fmt"
)

func main() {
    const name, age = "Kim", 22
    fmt.Printf("%s is %d years old.", name, age)
}
Enter fullscreen mode Exit fullscreen mode

Will print:

Kim is 22 years old.
Enter fullscreen mode Exit fullscreen mode

The interesting thing is that when the same exact program is compiled using Web Assembly, we get a different result. If you want to try it, copy the above program and run it here.

Spoiler alert: It doesn’t print anything.

However, if you change the program slightly:

package main

import (
    "fmt"
)

func main() {
    const name, age = "Kim", 22
    // add a newline character
    fmt.Printf("%s is %d years old.\n", name, age)
}
Enter fullscreen mode Exit fullscreen mode

Then it may print the expected:

Kim is 22 years old.
Enter fullscreen mode Exit fullscreen mode

thought if you run the two programs back to back, you may actually find that this is printed instead:

Kim is 22 years old.Kim is 22 years old.
Enter fullscreen mode Exit fullscreen mode

Why?

As far as I’ve been able to gather, when compiled to Web Assembly, the fmt.Printf function is writing to a buffer, and that buffer is not cleared until a newline character is printed to standard out. In other words, you can call fmt.Printf as many times as you want, but nothing is printed until a \n character comes through standard output.

My current working theory is that it works this way because there is no way to print to the console in a browser without appending a newline. As an example, JavaScript’s console.log() always appends a newline.

I’m missing all the details I would like to have about why it works this way. If any of my readers have any more information that I can include here please hit me up on Twitter!

Thanks For Reading!

Follow us on Twitter @q_vault if you have any questions or comments

Take game-like coding courses on Qvault Classroom

Subscribe to our Newsletter for more educational articles

The post Unexpected Printf Behavior in Go WASM – Nothing Prints appeared first on Qvault.

Top comments (0)