执行顺序与代码顺序不同

执行顺序与代码顺序不同

问题描述:

I execute this code snippet in goland IDE but found the output order is NOTthe same as what I expected:

package main

import (
    "fmt"
    "errors"
)

func main() {

    println("===========================")
    println("---------------------------")
    r,_:= div(6,3)
    fmt.Println(r)
}

func div(x, y int) (int, error) {
    defer println("dispose...")
    if y == 0 {
        return 0, errors.New("division by zero")
    }
    return x / y, nil
}

output:

enter image description here

  1. why the out order is differ from code order
  2. why the output in different color(white & red), I use goland IDE by jetbrain

I could not reproduce in https://play.golang.org/p/2T5LOt7FRDn My Local env: windows 10 + go1.10.3 windows/amd64 + GoLand 2018.1.4

First, note that println() writes to os.Stderr.

https://golang.org/pkg/builtin/#println

...and writes the result to standard error

It seems Jetbrain's IDEs would show you Stderr lines at the end and in a different colour.

This is a smaller program that would let you reproduce the same behaviour:

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Fprintln(os.Stderr, "to stderr")
    fmt.Fprintln(os.Stdout, "to stdout")
}

You will see the output inverted, with the to stderr line shown in red.

You cannot reproduce this outside the IDE cause then stderr and stdout ouput will be interleaved.