var anonymousStruct = &struct {
Value int
Test func()
}{
Test: func() {
fmt.Println(anonymousStruct.Value)
},
}
Looking at the code, I encountered an issue on line 6: the function "Test" cannot access the parameter "Value". Is there a way for the function to access "Value" without passing it as a parameter again, similar to "anonymousStruct.Test(anonymousStruct.Value)"? In other words, can an anonymous struct have methods instead of functions in Go? Thank you for your guidance.
You cannot declare methods to anonymous struct as a method declaration can only contain a named type (as the receiver).
Besides that, anonymous structs can have methods if they embed types that have methods (they get promoted).
In your example you cannot refer to the anonymousStruct
variable in the composite literal, because the variable will be in scope only after the declaration (after the composite literal). See Spec: Declarations and scope; example: Define a recursive function within a function in Go.
So for example you may initialize the function field after the variable declaration:
var anonymousStruct = &struct {
Value int
Test func()
}{Value: 3}
anonymousStruct.Test = func() {
fmt.Println(anonymousStruct.Value)
}
anonymousStruct.Test()
This will output (try it on the Go Playground):
3