打印输出
-
PrintXX()
-
FprintXX()
-
FprintXX
-
FprintXX在Go Web中使用比较多,把内容写到响应流中.
-
以Fprintln()举例,源码如下
-
// Fprintln formats using the default formats for its operands and writes to w. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { p := newPrinter() p.doPrintln(a) n, err = w.Write(p.buf) p.free() return }
-
-
第一个返回值表示输出内容长度(字节数),第二个返回值表示错误,如果没有错误取值nil
-
Fprintln()输出后会添加换行符,所以长度比内容多1个
-
-
// doPrintln is like doPrint but always adds a space between arguments // and a newline after the last argument. func (p *pp) doPrintln(a []interface{}) { for argNum, arg := range a { if argNum > 0 { p.buf.WriteByte(' ') } p.printArg(arg, 'v') } p.buf.WriteByte('\n')//此处多添加了换行 }
func main() { fmt.Fprint(os.Stdout, "内容1")//向流中写入内容,多个内容之间没有空格 fmt.Fprintln(os.Stdout, "内容2")//向流中写入内容后额外写入换行符,多个内容之间空格分割 fmt.Fprintf(os.Stdout, "%s", "内容3")//根据verb格式向流中写入内容 }
PrintXX
func main() { fmt.Println("内容","内容")//输出内容后换行 fmt.Print("内容","内容")//输出内容后不换行 fmt.Printf("verb","内容")//根据verb输出指定格式内容 }
- 以Println()举例,源码如下
// Println formats using the default formats for its operands and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func Println(a ...interface{}) (n int, err error) { return Fprintln(os.Stdout, a...) }
- 可以看出Println()底层实际是Fprintln(),返回值依然是内容长度和错误信息
SPrintXX
-
以Sprintln()举例,和Println()主要的区别是:
-
Sprintln()把形成结果以字符串返回,并没有打印到控制台
-
Println()把结果打印到控制台,返回内容长度和错误
-
-
所以从严格意义角度讲SprintXX不是打印输出,而更像字符串转换
-
源码如下
// Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. func Sprintln(a ...interface{}) string { p := newPrinter() p.doPrintln(a) s := string(p.buf) p.free() return s }
- 依然支持三种写法
func main() { fmt.Sprint("内容1", "内容12") fmt.Sprintln("内容2") fmt.Sprintf("%s", "内容3") }