-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
What is the URL of the page with the issue?
https://go.dev/ref/spec#Package_initialization
What is your user agent?
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
Screenshot
What did you do?
Does the variable c
depends on the variables a
and b
in the following program?
package main
import "fmt"
var a = 10
var b = 20
var c = func() int {
return a + b
}()
func main() {
fmt.Println(a, b, c)
}
In my understanding of the specification (package initialization), we have the following references:
- a reference to the variable is an identifier to that variable - 1. rule
- a reference to the function is an identifier to that function (it doesn't matter if it's invoked) - 1. rule
- a reference to the method is a selector
t.m
wheret
is non-interface type (it doesn't matter if it's invoked) - 2. rule
Additionally, spec says - 3. rule:
A variable, function, or method x depends on a variable y if x's initialization expression or body (for functions and methods) contains a reference to y or to a function or method that depends on y.
Back to my example. It is clear that "anonymous" function depends on the a
and b
, but does c
depend on the a
and b
? Spec says that c
's initialization expression must contain reference to the function that depends on the a
and b
and my understanding is that this reference to the function (according to the 1. rule) is only by identifier, but not by "anonymous" function / function literal. Therefore, the reference to the function is defined by the 1st rule (same as the reference to the method is defined by the 2. rule).
For me, this case is unspecified (same as with methods on interfaces).
However, when I print c
it gives 30
(it's okay to me, since it is unspecified; it can also be 0
, 10
, 20
). Also, my colleagues and AI tools say that the dependency also holds in this case...
Who is right, what is true?
What did you see happen?
I see that the result of the variable c
is 30
, but I'm not sure if this is "random" (since it is not specified) or the spec guarantees it even for the anonymous functions / function literals.
What did you expect to see?
Resolving potential ambiguity. If I'm right, it would be great to potentially add an example with a function literal (as was done for interfaces and methods).