Difference between fmt.Println() and println() in Go

前端 未结 5 1674
北海茫月
北海茫月 2020-12-07 12:02

As illustrated below, both fmt.Println() and println() give same output in Go: Hello world!

But: how do they differ from each

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 12:31

    Interesting Example:

    ➜  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
    :1: .this does not escape
    0xc000074f47 0xc000074f47 false
    &{} &{} true
    

    It is something difference between println and fmt.Printf.

提交回复
热议问题