考虑一下,
package main
import "fmt"
func main() {
name := "johnny"
fmt.Println("Hello world %s\n", name)
}
打印出来,
Hello World %s 强尼
为什么我得到的是 %s 而不是这个,
package main
import "fmt"
func main() {
name := "johnny"
fmt.Printf("Hello world %s\n", name)
}
哪个打印 Hello world johnny?
我试图从 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:
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).
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).
但我无法理解这是否会影响我的程序。
最佳答案
Printf
中的f
用于“格式化”。这就是为什么 %?
动词会做任何事情,因为该函数是为它们解析而构建的。 Println
没有这种格式。
格式化不是某些语言中字符串的属性(也许您和我一样来自 Python?)
关于go - 为什么 Go 中的 fmt.Println 会打印动词 %s 字面值而不是值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33573483/