go - 为什么 Go 中的 fmt.Println 会打印动词 %s 字面值而不是值?

标签 go

考虑一下,

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:

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

但我无法理解这是否会影响我的程序。

最佳答案

Printf 中的f 用于“格式化”。这就是为什么 %? 动词会做任何事情,因为该函数是为它们解析而构建的。 Println 没有这种格式。

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

关于go - 为什么 Go 中的 fmt.Println 会打印动词 %s 字面值而不是值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33573483/

相关文章:

arrays - 使用 go 中的范围选择 2D slice 的 2D 子 slice

javascript - 如何将 Golang 中的 [][]byte 发送到浏览器以将其解码为图像

go - 超时时的 Nats.io QueueSubscribe 行为

go - 如何收听N个 channel ? (动态选择语句)

如果我包装我的对象,Golang 转换为自定义类型会失败

go - 导入的 Golang 包说未定义/不可用

sql - If/Else 语句中的 Golang Postgres 语法错误

selenium - Go - 我如何安装selenium以在go语言中使用它?

go - 运行外部 python 脚本并检查退出状态

reflection - 我可以在 Go 中使用反射创建一个新函数吗?