Can anonymous structs have methods in Go?

王林
Release: 2024-02-08 20:54:03
forward
812 people have browsed it

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

Question content

var anonymousStruct = &struct {
    Value int
    Test  func()
}{
    Test: func() {
        fmt.Println(anonymousStruct.Value)
    },
}
Copy after login

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()
Copy after login

This will output (try it on Go Playground):

3
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!