152

如下图所示,两者fmt.Println()println()在 Go 中给出相同的输出:Hello world!

但是:它们之间有何不同?

片段1、使用fmt包;

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello world!")
}

Snippet 2,没有fmt包装;

package main

func main() {
    println("Hello world!")
}
4

5 回答 5

136

println是一个内置函数(进入运行时),最终可能会被删除,而fmt包在标准库中,它将持续存在。请参阅有关该主题的规范

对于语言开发人员来说,没有依赖项很方便println,但要走的路是使用fmt包或类似的东西(log例如)。

正如您在实现中看到的那样,这些print(ln)功能甚至不是为了远程支持不同的输出模式而设计的,主要是一个调试工具。

于 2013-02-04T04:28:38.263 回答
127

以尼莫的回答为基础:

println是语言中内置的函数。它位于规范的 Bootstrapping 部分。从链接:

当前的实现提供了几个在引导期间有用的内置函数。这些功能已记录在案以确保完整性,但不保证保留在该语言中。他们不返回结果。

Function   Behavior

print      prints all arguments; formatting of arguments is implementation-specific
println    like print but prints spaces between arguments and a newline at the end

因此,它们对开发人员很有用,因为它们缺少依赖项(内置在编译器中),但在生产代码中却没有。同样重要的是要注意printprintln 报告给stderr,而不是stdout

但是,由 提供的系列fmt是在生产代码中构建的。stdout除非另有说明,否则他们可预测地向 报告。它们更加通用(fmt.Fprint*可以报告给任何类型io.Writer,例如os.Stdout, os.Stderr,甚至是net.Conn类型。)并且不是特定于实现的。

大多数负责输出的包都fmt具有依赖项,例如log. 如果您的程序将在生产中输出任何内容,fmt那么很可能是您想要的包。

于 2013-02-04T04:51:26.450 回答
7

我可以在这里看到区别:

rangeOverIntsAndStrings(1, 5)

func rangeOverIntsAndStrings(args ...interface{}) {
    for _, v := range args {
        println(v)
    }
}

// 输出

(0x108f060,0x10c5358)
(0x108f060,0x10c5360)

对比

func rangeOverIntsAndStrings(args ...interface{}) {
    for _, v := range args {
        fmt.Println(v)
    }
}

// 输出

1
5
于 2019-09-21T16:20:50.477 回答
-1

有趣的例子:

➜  netpoll git:(develop) ✗ cat test.go
package main

import "fmt"

func main() {
        a := new(struct{})
        b := new(struct{})
        println(a, b, a == b)

        c := new(struct{})
        d := new(struct{})
        fmt.Printf("%v %v %v\n", c, d, c == d)
}
➜  netpoll git:(develop) ✗ go run test.go       
0xc000074f47 0xc000074f47 false
&{} &{} true
➜  netpoll git:(develop) ✗ go run -gcflags="-m" test.go
# command-line-arguments
./test.go:12:12: inlining call to fmt.Printf
./test.go:6:10: new(struct {}) does not escape
./test.go:7:10: new(struct {}) does not escape
./test.go:10:10: new(struct {}) escapes to heap
./test.go:11:10: new(struct {}) escapes to heap
./test.go:12:35: c == d escapes to heap
./test.go:12:12: []interface {} literal does not escape
<autogenerated>:1: .this does not escape
0xc000074f47 0xc000074f47 false
&{} &{} true

println这是和之间的区别fmt.Printf

于 2020-05-27T09:07:34.343 回答
-2

至于区别,是一个例子。

println()打印一个指向函数测试地址的指针。

fmt.Println()打印函数的地址。

于 2016-09-16T15:20:25.443 回答