Home  >  Article  >  Backend Development  >  Can anonymous structs have methods in Go?

Can anonymous structs have methods in Go?

王林
王林forward
2024-02-08 20:54:03799browse

Go 中匿名结构体可以有方法吗?

Question content

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.


Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete