Skip to content

doc: can not find document about type/const/var declare reference rule in the package scope and a function scope. #29168

@bronze1man

Description

@bronze1man

Please tell me wrong, if this stuff is already appeared in the document, I just do not find it.

I am writing a tool to find all reference source code of a program. I notice that follow program can not compile:

package main

import "fmt"

func main(){
	type t1 struct{
		f1 t2
	}
	type t2 struct{
	}
	fmt.Println(&t1{})
}

you will get an error main.go:7:6: undefined: t2.

But following program can compile:

package main

import "fmt"

func main(){
	fmt.Println(&t1{})
}

type t1 struct{
	f1 t2
}
type t2 struct{
}

So where is the document of type declare order in different scope?Will this behavior change in next golang version?

The best thing I can find is here: https://golang.org/ref/spec#Declarations_and_scope

The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.
The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.

But it is not same as the type/const/var reference rule in package scope. It does match the behavior in the function scope.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions