Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can an anonymous struct have methods in Go?

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 effect 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading