Home >Backend Development >Golang >Can anonymous structs have methods in Go?
var anonymousStruct = &struct { Value int Test func() }{ Test: func() { fmt.Println(anonymousStruct.Value) }, }
Looking at the code, I encountered a problem on line 6: function "Test" cannot access parameter "Value". Is there a way to give a function access to "Value" without passing it as a parameter again, similar to "anonymousStruct.Test(anonymousStruct.Value)"? In other words, can anonymous structs in Go have methods instead of functions? Thank you for your guidance.
You cannot declare a method as an anonymous structure because method declarations can only contain named types (as receivers).
In addition to this, anonymous structs can have methods if they are embedded in types that have methods (they will be promoted).
In your example, you cannot reference the anonymousStruct variable within the compound literal
because the variable is only in scope after it is declared (after the compound literal). See Specification: Declarations and Scope; Example: Defining a recursive function within a function Let's go.
For example, you can initialize function fields after 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 Go Playground):
3
The above is the detailed content of Can anonymous structs have methods in Go?. For more information, please follow other related articles on the PHP Chinese website!