johnny
johnny

Reputation: 19755

Why does fmt.Println in Go print the verb %s literal instead of the value?

Consider,

package main
import "fmt"

func main() {
  name := "johnny"
  fmt.Println("Hello world %s\n", name)
}

prints out,

Hello world %s johnny


Why do I get the %s instead of this,

package main
import "fmt"

func main() {
  name := "johnny"
  fmt.Printf("Hello world %s\n", name)
}

which prints Hello world johnny?

I have tried to figure out the answer from the documentation,

If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %v %x %X), the following two rules apply:

  1. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

  2. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

But I'm having trouble understanding if this is affecting my program.

Upvotes: 3

Views: 2095

Answers (2)

Adam Smith
Adam Smith

Reputation: 54243

the f in Printf is for "Formatting." That's why the %? verbs do anything at all, because the function is built to parse for them. Println does no such formatting.

Formatting isn't a property of strings like in some languages (maybe you, like myself, came from Python?)

Upvotes: 4

evanmcdonnal
evanmcdonnal

Reputation: 48154

Println just prints the string and appends a newline to it. Printf is short for 'print format' and is based off the C library which is where the conventions for format specifiers ect come from.

Simple answer is it's as designed. If you want to use format specifiers you gotta call the format method.

Upvotes: 1

Related Questions