Golang中println和fmt.Println区别解析

Golang 中打印数据通常使用 fmt.Println() 方法,也可以使用内置的 println() 方法。这两个方法大家可能都使用过,它们的区别是什么呢?

println()

先看下 println() 方法的注释:

// The println built-in function formats its arguments in an
// implementation-specific way and writes the result to standard error.
// Spaces are always added between arguments and a newline is appended.
// Println is useful for bootstrapping and debugging; it is not guaranteed
// to stay in the language.

可以看出 println() 是内置方法,属于builtin 包(builtin包是Golang预声明的包,不需要 import 即可使用),可以传入多个Type类型(pointer、channel、func、 interface、map和slice 类型)参数,将结果写入标准错误。主要用于调试,不保证在未来的 Golang 版本中还保留此方法。

fmt.println()

再看下 fmt.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

可以看出 fmt.println() 属于 fmt 包,可以传入多个 interface 类型的参数,将结果写入标准输出。返回两个参数——写入的字节数和error。

println() 和 fmt.println() 的区别

通过上面的注释和说明可以看出如下区别:

  • 所属的包不同。println() 属于 builtin 包,fmt.println() 属于 fmt 包。

  • 输出方式不同。println() 输出到标准错误(STDERR),fmt.println() 输出到标出输出(STDOUT)。

  • 返回值不同。println()无返回值,fmt.println()有两个返回值——写入的字节数和error。

  • println() 输出结果可能与预期结果顺序不一致,而 fmt.Println() 输出结果与预期结果完全一致(这个特性是由标准错误和标准输出的特性决定的)。

  • println() 不能传入数组和结构体类型的参数。

  • 对于组合类型的参数,println() 输出的结果是参数的地址,而 fmt.Println() 输出的结果是字面量。

作者:路多辛原文地址:https://blog.csdn.net/luduoyuan/article/details/129602905

%s 个评论

要回复文章请先登录注册