Skip to content

spec: package initialization issue #25474

@Happyholic1203

Description

@Happyholic1203

The following piece of code produces different result from SPEC

$ cat main.go
package main

import "fmt"

var (
	a = c + b
	b = f()
	c = f()
	d = 3
)

func f() int {
	d++
	return d
}

func main() {
	fmt.Println(a, b, c, d)
}
$ go run main.go
9 5 4 5

Following the SPEC, b should be initialized before c, so instead of 9 5 4 5, 9 4 5 5 is expected, according to the SPEC:

... package-level variables are initialized in declaration order but after any of the variables they depend on.

However, if we change a = c + b to a = b + c, then b is initialized before c.

So it seems like the order of presence precedes the order of declaration, deviating the SPEC.

go version: 1.10.2 darwin/amd64

go env:

GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/user/Library/Caches/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/user/go"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.10.2/libexec"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.10.2/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/d3/8sk_rdjx1s703xh89gb4x38h0000gn/T/go-build710804438=/tmp/go-build -gno-record-gcc-switches -fno-common"

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions