Skip to main content

fmt 包、Print、Println、 Printf、注释

fmt 包、Print、Println、Printf

Golang 中要打印一个值需要引入 fmt

import "fmt"

fmt 包里面给我们提供了一些常见的打印数据的方法,比如:PrintPrintlnPrintf, 在我们实际开发中 PrintlnPrintf 用的非常多。

  • 一次输入多个值的时候 Println 中间有空格 Print 没有
fmt.Println("go", "python", "php", "javascript") // go python php javascript 
fmt.Print("go", "python", "php", "javascript") // gopythonphpjavascript
  • Println 会自动换行,Print 不会
package main 
import "fmt"
func main() {
fmt.Println("hello")
fmt.Println("world") // hello // world
fmt.Print("hello")
fmt.Print("world") // helloworld
}
  • PrintlnPrintf 区别:
Printf 是格式化输出,在很多场景下比 Println 更方便,举个例子:
a := 10 
b := 20
c := 30
fmt.Println("a=", a, ",b=", b, ",c=", c) //a= 10 ,b= 20 ,c= 30
fmt.Printf("a=%d,b=%d,c=%d", a, b, c) //a=10,b=20,c=30
tip
  • %d 是占位符,表示数字的十进制表示。Printf 中的占位符与后面的数字变量一一对应。

更多的占位符参考:http://docscn.studygolang.com/pkg/fmt/

注释

  • win 下面 ctrl+/ 可以快速的注释一样。
  • mac 下面 command+/ 也可以快速的注释一样。