Understand the function types in Golang

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.