how print variable values in Go with fmt.Printl?

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

how print variable values in Go with fmt.Printl?

问题

我有以下代码片段:

x_variable := 12311
fmt.Println("message", "X变量的值为'+x_variable+',现在在屏幕上打印出来")

我该如何使其工作?
我在Go playground中尝试过,但无法正确打印出该值。

英文:

I have the below code snippet:

x_variable := 12311
fmt.Println("message", "X variable has the value '+x_variable+' printed in the screen now")

How can I make that work?
I've tried that in the Go playground but couldn't figure it out how to print the vaue properly.

答案1

得分: 0

包 main

import (
    "fmt"
)

func main() {
    x_variable := 12311
    fmt.Printf("message X变量的值为 %d,现在在屏幕上打印出来", x_variable)
}
英文:
package main

import (
	"fmt"
)

func main() {
	x_variable := 12311
	fmt.Printf("message X variable has the value %d printed in the screen now", x_variable)
}

</details>



# 答案2
**得分**: -2

你需要的是[Sprintf](https://pkg.go.dev/fmt#Sprintf)。

你可以在那里找到一个[示例](https://go.dev/play/p/geqloT6q3_H)。

由于你想打印一个整数,你可以使用`%d`修饰符。

请记住,`Sprintf`系列函数不会自动插入换行符,所以你还需要使用`\n`。

<details>
<summary>英文:</summary>

What you need is [Sprintf](https://pkg.go.dev/fmt#Sprintf)


You can find already an [example](https://go.dev/play/p/geqloT6q3_H) there.

Since you want to print an integer, you can use the `%d` modifier.

Keep in mind that `Sprintf` family does not insert newline automatically, so you will also need `\n`

</details>



huangapple
  • 本文由 发表于 2022年3月11日 01:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/71428654.html
匿名

发表评论

匿名网友

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

确定