1

I wrote simple codes to test println and fmt.Println, but when I ran the code, it printed different results almost everytime. I tried to google the difference between println and fmt.Println but got nothing. Is there any one who knows the real difference or the priority or the sequence of those two function?

Here is the code:

package main
import (
    "fmt"
)

func main(){
    println("a")
    fmt.Println("b")
    println("c")
    fmt.Println("d")

    p()
}

func p(){
    println("e")
    fmt.Println("f")
    println("g")
    fmt.Println("h")
}

Thanks!

sillydong
  • 61
  • 1
  • 5
  • 4
    Why are you interested in using `println()`? This is not a formal part of the language spec and can disappear in the future. See: http://golang.org/ref/spec#Bootstrapping – Grokify Jun 27 '15 at 15:00
  • Why is there a semicolon after `println("a")` – Kolja Jun 27 '15 at 15:05
  • @koljanep: The semicolon is not relevant to the question: [Semicolons](http://golang.org/ref/spec#Semicolons). – peterSO Jun 27 '15 at 15:16

2 Answers2

4

Builtin functions

func println

func println(args ...Type)

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.

Package fmt

func Println

func Println(a ...interface{}) (n int, err error)

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() uses stdout; println() uses stderr.

As expected, two different functions with different purposes give different results.

peterSO
  • 158,998
  • 31
  • 281
  • 276
  • 4
    To add color to this, standard error and standard out are two different output streams. There is no guarantee as to the order they are displayed to your terminal. If you chants fmt.Println to fmt.Fprintln(os.StdErr,"b") then they will interleve as you expect – David Budworth Jun 27 '15 at 15:21
  • This comment is the important part of the answer. – Stephan Dollberg Jun 27 '15 at 15:25
2

Best practice: only use fmt.Println("My text...")

Do not use println("My text...")

openwonk
  • 14,023
  • 7
  • 43
  • 39