douwen8118 2015-11-06 18:40
浏览 370
已采纳

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

Consider,

package main
import "fmt"

func main() {
  name := "johnny"
  fmt.Println("Hello world %s
", 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
", 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.

  • 写回答

2条回答 默认 最新

  • doudu161481 2015-11-06 18:44
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?