fmt.Fprint adds blanks outside playground

The specification of fmt.Fprint says "Spaces are added between operands when neither is a string ". This is written similarly in other fmt print func.

Fprint works as described on the playground so f.i.
import (
“fmt”
“os”
)

func main() {
w := os.Stdout
a := 10
b := 2
fmt.Fprint(w,“The following string prints blanks between numbers”,a,b," but not the following.")
fmt.Fprint(w,“No blanks are added”,a,“and this is according to specifications.”)
}
And the output reads :
The following string prints blanks between numbers10 2 but not the following.No blanks are added10and this is according to specifications.

As a side comment, blanks are always added with Fprintln.
When using Fprint on http.ResponseWriter, blanks are always added.
The behaviour looks inconsistent.
Is there a good reason ?

Thank you,

The issue disappears when Fprintf statements without format strings are removed. This doesn’t look like a good reason. Print statement print HTML strings.

I can’t reproduce that. This code:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello", 10, "bye\n")
}

results in this:

jb@syno:~ $ curl http://localhost:8080/
Hello10bye
jb@syno:~ $ 

which seems to be according to specs?

1 Like

I never really manage to locate the issue but I noticed while developing I used Fprint and Fprintf statements. Some Fprintf statement didn’t have any format string. Everything runs on the Google Cloud Platform. I cleaned all Fprintf and the issue disappeared.

I agree that on simple statements or a few short lines, it is impossible to reproduce the error. It seems to me that Fprintf without format string leaves something behind that is interpreted later or in a func as the “next” field which is then of a different type as the spec says.

Thanks anyway for the post.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.