'What does it mean for a function to have a method?
I'm seeing the following type definition:
type Getter func(ctx *context.T, key string) (Ticket, error)
And the following method defined on it:
func (g Getter) GetData(ctx *context.T, path ...string) (data []byte, err error) {
…
}
I'm also seeing the following variable definition:
var Client Getter = func(ctx *context.T, key string) (Ticket, error) {
return …
}
where:
type Ticket interface {
…
}
What'll happen with this code exactly?
Solution 1:[1]
tl;dr It won't compile because Cannot use 'func() (MyData, error) { return nil, nil }' (type func() (MyData, error)) as the type Getter. In other words, MyGetter does not match the type of Getter. Here's a go playground link.
There are a couple of things going on here:
- You're creating a type called
Getter. Any value that fulfills thisGettertype must be a function with zero input parameters and zero output parameters (keep this in mind for a second). - Go has first-class functions which means they can be assigned to variables, passed to parameters of other functions, or in this case methods can be added to a type whose underlying type is a function.
- Lastly, you're trying to assign a function with the signature
func() (MyData, error)to the typeGetterwhich is where you're getting the compile error I mentioned in the tl;dr. This compile error is because your typeGetterspecifies that any value of this type must be a function with zero input parameters and zero return parameters. You're trying to assign a function that does have return parameters.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
