How to use function types in go?

Time:2021-10-16

=How to use function types in go?

Function types is a very special type, which represents a collection of functions with the same input parameter type and return value type.

The following line of code defines a function type called greeting

  1. typeGreetingfunc(namestring)string

This type has two characteristics:

Only one parameter is received, and the type of the parameter is string

The return value also has only one parameter of type string

As long as a function satisfies these characteristics, it can convert the function into a function object of greeting type (that is, greet) in the following ways

  1. funcenglish(namestring)string{
  2. return”Hello,”+name
  3. }
  4.  
  5. //Function object converted to greeting type
  6. greet:=Greeting(english)
  7. //Or
  8. vargreetGreeting=english

As an object of greeting type, greet also owns all methods of greeting type, such as the following say method

  1. func(gGreeting)say(nstring){
  2. fmt.Println(g(n))
  3. }

Try calling directly, and there will be no error

  1. greet.say(“World”)

Put the above code together

  1. packagemain
  2.  
  3. import”fmt”
  4.  
  5. //Greetingfunctiontypes
  6. typeGreetingfunc(namestring)string
  7.  
  8. func(gGreeting)say(nstring){
  9. fmt.Println(g(n))
  10. }
  11.  
  12. funcenglish(namestring)string{
  13. return”Hello,”+name
  14. }
  15.  
  16. funcmain(){
  17. greet:=Greeting(english)
  18. greet.say(“World”)
  19. }
  20. //output:Hello,World

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]