为什么Go语言中的fmt.Println打印的是%s占位符的字面值而不是实际值?

huangapple go评论84阅读模式
英文:

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

问题

考虑一下,

package main
import "fmt"

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

输出结果为,

Hello world %s
johnny


为什么我得到的是 %s 而不是这个,

package main
import "fmt"

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

它输出的是 Hello world johnny?

我尝试从文档中找到答案,

> 如果格式(对于 Println 等,默认为 %v)对于字符串有效(%s %q %v %x %X),则适用以下两个规则:
>
> 4. 如果操作数实现了 error 接口,则将调用 Error 方法将对象转换为字符串,然后按照所需的动词(如果有)进行格式化。
>
> 5. 如果操作数实现了 String() string 方法,则将调用该方法将对象转换为字符串,然后按照所需的动词(如果有)进行格式化。

但我很难理解这是否会影响我的程序。

英文:

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:
>
> 4. 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).
>
> 5. 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.

答案1

得分: 3

Printf中的f代表"格式化"。这就是为什么%?这些占位符会起作用的原因,因为该函数被设计用于解析它们。而Println则不进行任何格式化。

格式化不是字符串的属性,就像某些语言中一样(也许你和我一样,来自Python?)

英文:

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?)

答案2

得分: 1

Println只是打印字符串并在其后添加一个换行符。Printf是“打印格式”的缩写,它基于C库,其中包含格式说明符等约定。

简单来说,这是按设计要求的。如果你想使用格式说明符,你需要调用格式化方法。

英文:

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.

huangapple
  • 本文由 发表于 2015年11月7日 02:40:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/33573483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定