I wanted to create a function of a certain type. I’ve found one way to do it, but there must be other, cleaner and nicer ways that do not include using var. What are the alternative ways to declare the function english of type Greeting?
package main
import "fmt"
type Greeting func(name string) string
func (g Greeting) exclamation(name string) string {
return g(name) + "!"
}
var english = Greeting(func(name string) string {
return "Hello, " + name
})
func main() {
fmt.Println(english("ANisus"))
fmt.Println(english.exclamation("ANisus"))
}
In the example above, I can’t exchange var english = Greeting... with english := Greeting..., nor can I remove the Greeting(func ...) and just have the func stand alone since then I won’t be able to access the exclamation method.
If mentioning
varis your main problem, you can drop it easily, by changing=into:=, like this:But you don’t even have to cast your function into
Greeting. The spec says this about function types:And this about type identity:
This means that each function has its own function type. If two functions have the same signature (parameter and result types), they share one function type. By writing
type Greeting func...you’re just giving a name to a particular function type, not defining a new one.So the following code works, and I hope shows the right way to work with function types in Go:
Notice that I also dropped semicolon and parenthesis from your
englishfunction. Go developers don’t use these punctuations if they don’t have to.UPDATE: Now that you’ve provided a sample code I can clearly understand the problem.
For this purpose your code is good enough and there are not much other ways of doing it. If you like you can cast just before calling the method:
But I’m not sure this is an improvement. I’m just saying that for what you want to do there does not seem to be other ways to write the code.
That is, if we don’t want to change your types. I mean, the whole idea of calling a method on a function type seems a little weird. Not that it’s wrong, but a little rare. Another way of achieving the same effect in a more usual way is through a struct type and having a field for the function. Something like this:
Here
englishandfrenchshow two different ways of coding the same thing. Again, I’m not saying that this is the better solution, but a more usual and more flexible way of achieving the same effect.