Let's look at an example:
Package main Import "FMT" //Greeting function Typestype greeting func (name string) string func say (g greetin g, n string) { FMT. Println (g (n))} func 中文版 (name string) string { return "Hello," + name} Func main () { say (English, "Wo Rld ")}
Output: Hello, World
The Say () function requires a greeting type to be passed in, because the parameters and return values of the Chinese function are the same as greeting, where the concept of the reference interface can be used for type conversions. Let's do this in a different way:
Package main Import "FMT" //Greeting function Typestype greeting func (name string) string func (g greeting) Say (n string) { FMT. Println (g (n))} func 中文版 (name string) string { return "Hello," + name} Func main () { g: = Greeting (中文版) G.say ("World")}
The same output Hello, world, just adds the Say () method to the greeting type. As stated above, the function type is a collection of functions that represent all the same parameters and return types. We first declare a function of the Func (name string) string as the greeting type, and then we convert the Chinese function to the greeting type by greeting (中文版). With this conversion, we can call the Say () method of the greeting type by the variable G.
Package main Import "FMT" //Greeting function Typestype greeting func (name string) string func (g greeting) s Ay (n string) { FMT. Println (g (n))} func 中文版 (name string) string { return "Hello," + name} func French (name string) string {
return "Bonjour," + name} Func main () { g: = Greeting (中文版) G.say ("World") g = Greeting (French) G.say ("World")}
Output:
Hello, World
Bonjour, World
Transferred from: Https://www.jianshu.com/p/fc4902159cf5