Featured image of post Go中不同print的区别

Go中不同print的区别

末尾加ln的println,加f的printf

  package main
  
  import (
      "fmt"
  )
  
  func main() {
      name, age := "1", "2"
      fmt.Print(name, age,"\n")
      w, b := 1, 2
      fmt.Print(w, b)
  
      // It is conventional not to worry about any
      // error returned by Print.
  
  }

结果输出:

  12
  1 2

末尾加 f 格式化输出, 如 Printf

  package main
  
  import (
      "fmt"
  )
  
  func main() {
      const name, age = "Kim", 22
      fmt.Println("%s is %d years old.\n",name,age)
  
      // It is conventional not to worry about any
      // error returned by Println.
  
  }

结果输出: Kim is 22 years old.

Println: 在两个元素间都会产生一个空格, 同时还会在末尾添加换行符

  package main
  
  import (
      "fmt"
  )
  
  func main() {
      const name, age = "Kim", 22
      fmt.Println(name, "is", age, "years old.")
  
      // It is conventional not to worry about any
      // error returned by Println.
  
  }

结果是: Kim is 22 years old. 默认是如果两个都不是字符串则加空格,返回字节数和error

末尾ln表示始终添加空格,并且追加换行符

前面添加s

对print来说表示返回字节数和error更改为字符串

func Sprint(a …interface{}) string
func Sprintf(format string, a …interface{}) string
func Sprintln(a …interface{}) string

对scan来说表示可以输入字符

func Sscan(str string, a …interface{}) (n int, err error)
func Sscanf(str string, format string, a …interface{}) (n int, err error)
func Sscanln(str string, a …interface{}) (n int, err error)

Fprint 是可以

func Fprint(w io.Writer, a …interface{}) (n int, err error)
当两个都不是字符串时添加空格,同时返回有多少byte和错误

func Fprintf(w io.Writer, format string, a …interface{}) (n int, err error)
可以格式化输出,并且返回多少byte和错误

func Fprintln(w io.Writer, a …interface{}) (n int, err error)
原始格式输出,在运算符之间添加空格,并且追加换行符,并且返回多少byte和错误,

func Print(a …interface{}) (n int, err error)
当两个都不是字符串时添加空格

func Printf(format string, a …interface{}) (n int, err error)
可以格式化输出

func Println(a …interface{}) (n int, err error)
原始格式输出,在运算符之间添加空格,并且追加换行符

func Fscan(r io.Reader, a …interface{}) (n int, err error)

Licensed under CC BY-NC-SA 4.0