你知道Golang中println和fmt.Println有什么区别吗?
创始人
2025-05-29 09:01:25

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() 输出的结果是字面量。

相关内容

热门资讯

印度政府:正调查苹果手机信息泄... 7月4日消息,印度电子和信息技术部秘书克里希南7月2日表示,政府正就塔塔电子大规模数据泄露事件展开调...
SK海力士据悉考虑在巨额ADR... 7月4日消息,据报道,SK海力士公司正考虑将其美国上市所得款项中约0.5%支付给参与该交易的银行。最...
伊朗为已故最高领袖哈梅内伊举行... 7月4日消息,当地时间7月4日,伊朗在首都德黑兰为已故最高领袖阿里·哈梅内伊举行公众告别与悼念仪式。...
7-11起诉耐克,指控其新鞋配... 7月4日消息,据报道,跨国连锁零售公司7-Eleven(7-11)已在美国得克萨斯州联邦法院起诉运动...
斯洛伐克称不会承担北约峰会上提... 7月4日消息,斯洛伐克总理菲佐当地时间7月3日表示,即将在土耳其安卡拉举行的北约峰会所通过的决议,不...