One place for hosting & domains

      Functions

      Learning Go Functions, Loops, and Errors – A Tutorial


      Updated by Linode Contributed by Mihalis Tsoukalos

      Introduction

      Go is a modern, open source, and general-purpose programming language that began as an internal Google project and was officially announced at the end of 2009. Go was inspired by many other programming languages including C, Pascal, Alef, and Oberon. Its spiritual fathers were Robert Griesemer, Ken Thomson, and Rob Pike, who all designed Go as a language for professional programmers that want to build reliable, robust, and efficient software. Apart from its syntax and its standard functions, Go comes with a rich standard library.

      In this Guide

      This guide will cover the following topics:

      Note

      This guide was written with Go version 1.13.

      Before You Begin

      1. You will need Go installed on your computer. To get it, go to Go’s official download page and get the installer for your operating system, or you can install it from source. Follow the installation instructions for your operating system.

      2. Add /usr/local/go/bin to the PATH environment variable:

        export PATH=$PATH:/usr/local/go/bin
        

        You may need to restart your shell for this change to apply.

      The Advantages of Go

      Although Go is not perfect, it has many advantages, including the following:

      • It is a modern programming language that was made by experienced developers for developers.
      • The code is easy to read.
      • Go keeps concepts orthogonal, or simple, because a few orthogonal features work better than many overlapping ones.
      • The compiler prints practical warnings and error messages that help you solve the actual problem.
      • It has support for procedural, concurrent, and distributed programming.
      • Go supports garbage collection so you do not have to deal with memory allocation and deallocation.
      • Go can be used to build web applications and it provides a simple web server for testing purposes.
      • The standard Go library offers many packages that simplify the work of the developer.
      • It uses static linking by default, which means that the produced binary files can be easily transferred to other machines with the same OS and architecture. As a consequence, once a Go program is compiled successfully and the executable file is generated, the developer does not need to worry about dependencies and library versions.
      • The code is portable, especially among UNIX machines.
      • Go can be used for writing UNIX systems software.
      • It supports Unicode by default which means that you do not need any extra code for printing characters from multiple human languages or symbols.

      Executing Go code

      There are two kinds of Go programs: autonomous programs that are executable, and Go libraries. Go does not care about an autonomous program’s file name. What matters is that the package name is main and that there is a single main() function in it. This is because the main() function is where program execution begins. As a result, you cannot have multiple main() functions in the files of a single project.

      A Simple Go program

      This is the Go version of the Hello World program:

      ./helloworld.go
      1
      2
      3
      4
      5
      6
      7
      8
      9
      
      package main
      
      import (
          "fmt"
      )
      
      func main() {
          fmt.Println("Hello World!")
      }
      • All Go code is delivered within Go packages. For executable programs, the package name should be main. Package declarations begin with the package keyword.

      • Executable programs should have a function named main() without any function parameters. Function definitions begin with the func keyword.

      • Go packages might include import statements for importing Go packages. However, Go demands that you use some functionality from each one of the packages that you import. There is a way to bypass this rule, however, it is considered a bad practice to do this.

        The helloworld.go file above imports the fmt package and uses the fmt.Println() function from that package.

        Note

        All exported package functions begin with an uppercase letter. This follows the Go rule: if you export something outside the current package, it should begin with an uppercase letter. This rule applies even if the field of the Go structure or the global variable is included in a Go package.

      • Go statements do not need to end with a semicolon. However, you are free to use semicolons if you wish. For more information on formatting with curly braces, see the section below.

      1. Now that you better understand the helloworld.go program, execute it with the go run command:

        go run helloworld.go
        

        You will see the following output:

          
        Hello World!
        
        

        This is the simplest of two ways that you can execute Go code. The go run command compiles the code and creates a temporary executable file that is automatically executed and then it deletes that temporary executable file. This is similar to using a scripting programming language.

      2. The second method to execute Go code is to use the build command. Run the following command to use this method:

        go build helloworld.go
        

        The result of that command is a binary executable file that you have to manually execute. This method is similar to the way you execute C code on a UNIX machine. The executable file is named after the Go source filename, which means that in this case the result will be an executable file named helloworld. Go creates statically linked executable files that have no dependencies to external libraries.

      3. Execute the helloworld file:

        ./helloworld
        

        You will see the following output:

          
        Hello World!
        
        

        Note

        The go run command is usually used while experimenting and developing new Go projects. However, if you need to transfer an executable file to another system with the same architecture, you should use go build.

      Formatting Curly Braces

      The following version of the “Hello World” program will not compile:

      ./curly.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      
      package main
      
      import (
          "fmt"
      )
      
      func main()
      {
          fmt.Println("Hello World!")
      }
      1. Execute the program above, and observer the error message generated by the compiler:

        go run curly.go
        
          
        # command-line-arguments
        ./curly.go:7:6: missing function body
        ./curly.go:8:1: syntax error: unexpected semicolon or newline before {
        
        
      • This error message is generated because Go requires the use of semicolons as statement terminators in many contexts and the compiler automatically inserts the required semicolons when it thinks that they are necessary. Putting the opening curly brace ({) on its own line makes the Go compiler look for a semicolon at the end of the previous line (func main()), which is the cause of the error message.

      • There is only one way to format curly braces in Go; the opening curly brace must not appear on it’s own line. Additionally, you must use curly braces even if a code block contains a single Go statement, like in the body of a for loop. You can see an example of this in the first version of the helloworld.go program or in the Loops in Go section.

      The Assignment Operator and Short Variable Declarations

      • Go supports assignment (=) operators and short variable declarations (:=).
      • With := you can declare a variable and assign a value to it at the same time. The type of the variable is inferred from the given value.
      • You can use = in two cases. First, to assign a new value to an existing variable and second, to declare a new variable, provided that you also give its type.

        For example, var aVariable int = 10, is equivalent to aVariable := 10 assuming aVariable is an int.

      • When you specifically want to control a variable’s type, it is safer to declare the variable and its type using var and then assign a value to it using =.

      Loops in Go

      The file loops.go demonstrates loops in Go:

      ./loops.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      
      package main
      
      import (
          "fmt"
      )
      
      func main() {
          for loopIndex := 0; loopIndex < 20; loopIndex++ {
              if loopIndex%10 == 0 {
                  continue
              }
      
              if loopIndex == 19 {
                  break
              }
              fmt.Print(loopIndex, " ")
          }
          fmt.Println()
      
          // Use break to exit the for loop
          loopIndex := 10
          for {
              if loopIndex < 0 {
                  break
              }
              fmt.Print(loopIndex, " ")
              loopIndex--
          }
          fmt.Println()
      
          // This is similar to a while(true) do something loop
          loopIndex = 0
          anExpression := true
          for ok := true; ok; ok = anExpression {
              if loopIndex > 10 {
                  anExpression = false
              }
      
              fmt.Print(loopIndex, " ")
              loopIndex++
          }
          fmt.Println()
      
          anArray := [5]int{0, 1, -1, 2, -2}
          for loopIndex, value := range anArray {
              fmt.Println("index:", loopIndex, "value: ", value)
          }
      }
      • There are two types of for loops in Go. Traditional for loops that use a control variable initialization, condition, and afterthought; and those that iterate over the elements of a Go data type such as an array or a map using the range keyword.

      • Go has no direct support for while loops. If you want to use a while loop, you can emulate it with a for loop.

      • In their simplest form, for loops allow you to iterate, a predefined number of times, for as long as a condition is valid, or according to a value that is calculated at the beginning of the for loop. Such values include the size of a slice or an array, or the number of keys on a map. However, range is more often used for accessing all the elements of a slice, an array, or a map because you do not need to know the object’s cardinality in order to process its elements one by one. For simplicity, this example uses an array, and a later example will use a slice.

      • You can completely exit a for loop using the break keyword. The break keyword also allows you to create a for loop without an exit condition because the exit condition can be included in the code block of the for loop. You are also allowed to have multiple exit conditions in a for loop.

      • You can skip a single iteration of a for loop using the continue keyword.

      1. Execute the loops.go program:

        go run loops.go
        

        You will see the following output:

          
        1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18
        10 9 8 7 6 5 4 3 2 1 0
        0 1 2 3 4 5 6 7 8 9 10 11
        index: 0 value:  0
        index: 1 value:  1
        index: 2 value:  -1
        index: 3 value:  2
        index: 4 value:  -2
            
        

      Functions in Go

      Functions are first class citizens in Go, which means that functions can be parameters to other functions as well as returned by functions. This section will illustrate various types of functions.

      Go also supports anonymous functions. These can be defined inline without the need for a name and they are usually used for implementing operations that require a small amount of code. In Go, a function can return an anonymous function or take an anonymous function as one of its arguments. Additionally, anonymous functions can be attached to Go variables. In functional programming terminology anonymous functions are called closures. It is considered a good practice for anonymous functions to have a small implementation and a local focus.

      Regular functions

      This section will present the implementation of some traditional functions.

      ./functions.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      
      package main
      
      import (
          "fmt"
      )
      
      func doubleSquare(firstNum int) (int, int) {
          return firstNum * 2, firstNum * firstNum
      }
      
      func namedMinMax(firstNum, secondNum int) (min, max int) {
          if firstNum > secondNum {
              min = secondNum
              max = firstNum
          } else {
              min = firstNum
              max = secondNum
          }
          return
      }
      
      func minMax(firstNum, secondNum int) (min, max int) {
          if firstNum > secondNum {
              min = secondNum
              max = firstNum
          } else {
              min = firstNum
              max = secondNum
          }
          return min, max
      }
      
      func main() {
          secondNum := 10
      
          square := func(numberToSquare int) int {
              return numberToSquare * numberToSquare
          }
          fmt.Println("The square of", secondNum, "is", square(secondNum))
      
          double := func(numberToDouble int) int {
              return numberToDouble + numberToDouble
          }
          fmt.Println("The double of", secondNum, "is", double(secondNum))
      
          fmt.Println(doubleSquare(secondNum))
          doubledNumber, squaredNumber := doubleSquare(secondNum)
          fmt.Println(doubledNumber, squaredNumber)
      
          value1 := -10
          value2 := -1
          fmt.Println(minMax(value1, value2))
          min, max := minMax(value1, value2)
          fmt.Println(min, max)
          fmt.Println(namedMinMax(value1, value2))
          min, max = namedMinMax(value1, value2)
          fmt.Println(min, max)
      }
      • The main() function takes no arguments and returns no arguments. Once the special function main() exits, the program automatically ends.

      • The doubleSquare() function requires a single int parameter and returns two int values, which is defined as (int, int).

      • All function arguments must have a name – variadic functions are the only exception to this rule.

      • If a function returns a single value, you do not need to put parenthesis around its type.

      • Because namedMinMax() has named return values in its signature, the min and max parameters are automatically returned in the order in which they were put in the function definition. Therefore, the function does not need to explicitly return any variables or values in its return statement at the end, and does not. minMax() function has the same functionality as namedMinMax() but it explicitly returns its values demonstrating that both ways are valid.

      • Both square and double variables in main() are assigned an anonymous function. However, nothing stops you from changing the value of square, double, or any other variable that holds the result of an anonymous function, afterwards. This means that both variables may have a different value in the future.

      1. Execute the functions.go program.

        go run functions.go
        

        Your output will resemble the following:

          
        The square of 10 is 100
        The double of 10 is 20
        20 100
        20 100
        -10 -1
        -10 -1
        -10 -1
        -10 -1
            
        

      Variadic functions

      Variadic functions are functions that accept a variable number of arguments. The most popular variadic functions in Go can be found in the fmt package. The code of variadic.go illustrates the creation and the use of variadic functions.

      ./variadic.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      
      package main
      
      import (
          "fmt"
      )
      
      func varFunc(input ...string) {
          fmt.Println(input)
      }
      
      func oneByOne(message string, sliceOfNumbers ...int) int {
          fmt.Println(message)
          sum := 0
          for indexInSlice, sliceElement := range sliceOfNumbers {
              fmt.Print(indexInSlice, sliceElement, "t")
              sum = sum + sliceElement
          }
          fmt.Println()
          sliceOfNumbers[0] = -1000
          return sum
      }
      
      func main() {
          many := []string{"12", "3", "b"}
          varFunc(many...)
          sum := oneByOne("Adding numbers...", 1, 2, 3, 4, 5, -1, 10)
          fmt.Println("Sum:", sum)
          sliceOfNumbers := []int{1, 2, 3}
          sum = oneByOne("Adding numbers...", sliceOfNumbers...)
          fmt.Println(sliceOfNumbers)
      }
      • The ... operator used as a prefix to a type like ...int is called the pack operator, whereas the unpack operator appends a slice like sliceOfNumbers.... A slice is a Go data type that is essentially an abstraction of an array of unspecified length.

      • Each variadic function can use the pack operator once. The oneByOne() function accepts a single string and a variable number of integer arguments using the sliceOfNumbers slice.

      • The varFunc function accepts a single argument and just calls the fmt.Println() function.

      • Another note about slices: the second call to oneByOne() is using a slice. Any changes you make to that slice inside the variadic function will persist after the function exits because this is how slices work in Go.

      1. Execute the variadic.go program:

        go run variadic.go
        

        The output will resemble the following

          
        [12 3 b]
        Adding numbers...
        0 1     1 2     2 3     3 4     4 5     5 -1     6 10
        Sum: 24
        Adding numbers...
        0 1     1 2     2 3
        [-1000 2 3]
            
        

      Functions and pointer variables

      Go supports pointers and this section will briefly present how functions can work with pointers. A future Go guide will talk about pointers in more detail, but here is a brief overview.

      ./fPointers.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      
      package main
      
      import (
          "fmt"
      )
      
      func getPointer(varToPointer *float64) float64 {
          return *varToPointer * *varToPointer
      }
      
      func returnPointer(testValue int) *int {
          squareTheTestValue := testValue * testValue
          return &squareTheTestValue
      }
      
      func main() {
          testValue := -12.12
          fmt.Println(getPointer(&testValue))
          testValue = -12
          fmt.Println(getPointer(&testValue))
      
          theSquare := returnPointer(10)
          fmt.Println("sq value:", *theSquare)
          fmt.Println("sq memory address:", theSquare)
      }
      • The getPointer() function takes a pointer argument to a float64, which is defined as varToPointer *float64, where returnPointer() returns a pointer to an int, which is declared as *int.
      1. Execute the fPointers.go program:

        go run fPointers.go
        

        The output will resemble the following:

          
        146.8944
        144
        sq value: 100
        sq memory address: 0xc00001a0b8
            
        

      Functions with Functions as Parameters

      Go functions can have functions as parameters.

      ./fArgF.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      
      package main
      
      import "fmt"
      
      func doubleIt(numToDouble int) int {
          return numToDouble + numToDouble
      }
      
      func squareIt(numToSquare int) int {
          return numToSquare * numToSquare
      }
      
      func funFun(functionName func(int) int, variableName int) int {
          return functionName(variableName)
      }
      
      func main() {
          fmt.Println("funFun Double:", funFun(doubleIt, 12))
          fmt.Println("funFun Square:", funFun(squareIt, 12))
          fmt.Println("Inline", funFun(func(numToCube int) int { return numToCube * numToCube * numToCube }, 12))
      }
      • The funFun() function accepts two parameters, a function parameter named functionName and an int value. The functionName parameter should be a function that takes one int argument and returns an int value.

      • The first fmt.Println() call in main() uses funFun() and passes the doubleIt function, without any parentheses, as its first parameter.

      • The second fmt.Println() call uses funFun() with squareIt as its first parameter.

      • In the last fmt.Println() statement the implementation of the function parameter is defined inside the call to funFun() using an anonymous function.

      1. Execute the fArgF.go program:

        go run fArgF.go
        

        The output will resemble the following:

          
        function1: 24
        function2: 144
        Inline 1728
            
        

      Functions Returning Functions

      Go functions can return functions.

      ./fRetF.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      
      package main
      
      import (
          "fmt"
      )
      
      func squareFunction() func() int {
          numToSquare := 0
          return func() int {
              numToSquare++
              return numToSquare * numToSquare
          }
      }
      
      func main() {
          square1 := squareFunction()
          square2 := squareFunction()
      
          fmt.Println("First Call to square1:", square1())
          fmt.Println("Second Call to square1:", square1())
          fmt.Println("First Call to square2:", square2())
          fmt.Println("Third Call to square1:", square1())
      }
      • squareFunction() returns an anonymous function with the func() int signature.

      • As squareFunction() is called two times, you will need to use two separate variables, square1 and square2 to keep the two return values.

      1. Execute the fRetF.go program:

        go run fRetF.go
        

        Your output will resemble the following:

          
        First Call to square1: 1
        Second Call to square1: 4
        First Call to square2: 1
        Third Call to square1: 9
            
        

        Notice that the values of square1 and square2 are not connected even though they both came from squareFunction().

      Errors in Go

      Errors and error handling are two important topics in Go. Go puts so much importance on error messages that it has a dedicated data type for errors, aptly named error. This also means that you can easily create your own error messages if you find that what Go gives you is not adequate. You will most likely need to create and handle your own errors when you are developing your own Go packages.

      Recognizing an error condition is one task, while deciding how to react to an error condition is another task. Therefore, some error conditions might require that you immediately stop the execution of the program, whereas in other error situations, you might just print a warning message and continue.

      ./errors.go
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      
      package main
      
      import (
          "errors"
          "fmt"
          "strconv"
      )
      
      func main() {
      
          customError := errors.New("My Custom Error!")
          if customError.Error() == "My Custom Error!" {
              fmt.Println("!!")
          }
      
          stringToConvert1 := "123"
          stringToConvert2 := "43W"
          _, err := strconv.Atoi(stringToConvert1)
          if err != nil {
              fmt.Println(err)
              return
          }
      
          _, err = strconv.Atoi(stringToConvert2)
          if err != nil {
              fmt.Println(err)
              return
          }
      }
      • The strconv.Atoi() function tries to convert a string into an integer, provided that the string is a valid integer, and returns two things, an integer value and an error variable. If the error variable is nil, then the conversion was successful and you get a valid integer. The _ character tells Go to ignore one, as in this case, or more of the return values of a function.

      • Most of the time, you need to check whether an error variable is equal to nil and then act accordingly. This kind of Go code is very popular in Go programs and you will see it and use it multiple times.

      • Also presented here is the errors.New() function that allows you to create a custom error message and errors.Error() function that allows you to convert an error variable into a string variable.

      1. Execute the errors.go program:

        go run errors.go
        

        Your output will resemble the following:

          
        !!
        strconv.Atoi: parsing "43W": invalid syntax
            
        

      Summary

      In this guide you learned the basics about the Go programming language, how to execute programs, how to write loops, how to handle errors, and you saw examples for various function types.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      Find answers, ask questions, and help others.

      This guide is published under a CC BY-ND 4.0 license.



      Source link

      How To Use Variadic Functions in Go


      Introduction

      A variadic function is a function that accepts zero, one, or more values as a single argument. While variadic functions are not the common case, they can be used to make your code cleaner and more readable.

      Variadic functions are more common than they seem. The most common one is the Println function from the fmt package.

      func Println(a ...interface{}) (n int, err error)
      

      A function with a parameter that is preceded with a set of ellipses (...) is considered a variadic function. The ellipsis means that the parameter provided can be zero, one, or more values. For the fmt.Println package, it is stating that the parameter a is variadic.

      Let’s create a program that uses the fmt.Println function and pass in zero, one, or more values:

      print.go

      package main
      
      import "fmt"
      
      func main() {
          fmt.Println()
          fmt.Println("one")
          fmt.Println("one", "two")
          fmt.Println("one", "two", "three")
      }
      

      The first time we call fmt.Println, we don’t pass any arguments. The second time we call fmt.Println we pass in only a single argument, with the value of one. Then we pass one and two, and finally one, two, and three.

      Let’s run the program with the following command:

      We’ll see the following output:

      Output

      one one two one two three

      The first line of the output is blank. This is because we didn’t pass any arguments the first time fmt.Println was called. The second time the value of one was printed. Then one and two, and finally one, two, and three.

      Now that we have seen how to call a variadic function, let’s look at how we can define our own variadic function.

      Defining a Variadic Function

      We can define a variadic function by using an ellipsis (...) in front of the argument. Let’s create a program that greets people when their names are sent to the function:

      hello.go

      package main
      
      import "fmt"
      
      func main() {
          sayHello()
          sayHello("Sammy")
          sayHello("Sammy", "Jessica", "Drew", "Jamie")
      }
      
      func sayHello(names ...string) {
          for _, n := range names {
              fmt.Printf("Hello %sn", n)
          }
      }
      

      We created a sayHello function that takes only a single parameter called names. The parameter is variadic, as we put an ellipsis (...) before the data type: ...string. This tells Go that the function can accept zero, one, or many arguments.

      The sayHello function receives the names parameter as a slice. Since the data type is a string, the names parameter can be treated just like a slice of strings ([]string) inside the function body. We can create a loop with the range operator and iterate through the slice of strings.

      If we run the program, we will get the following output:

      Output

      Hello Sammy Hello Sammy Hello Jessica Hello Drew Hello Jamie

      Notice that nothing printed for the first time we called sayHello. This is because the variadic parameter was an empty slice of string. Since we are looping through the slice, there is nothing to iterate through, and fmt.Printf is never called.

      Let’s modify the program to detect that no values were sent in:

      hello.go

      package main
      
      import "fmt"
      
      func main() {
          sayHello()
          sayHello("Sammy")
          sayHello("Sammy", "Jessica", "Drew", "Jamie")
      }
      
      func sayHello(names ...string) {
          if len(names) == 0 {
              fmt.Println("nobody to greet")
              return
          }
          for _, n := range names {
              fmt.Printf("Hello %sn", n)
          }
      }
      

      Now, by using an if statement, if no values are passed, the length of names will be 0, and we will print out nobody to greet:

      Output

      nobody to greet Hello Sammy Hello Sammy Hello Jessica Hello Drew Hello Jamie

      Using a variadic parameter can make your code more readable. Let’s create a function that joins words together with a specified delimiter. We’ll create this program without a variadic function first to show how it would read:

      join.go

      package main
      
      import "fmt"
      
      func main() {
          var line string
      
          line = join(",", []string{"Sammy", "Jessica", "Drew", "Jamie"})
          fmt.Println(line)
      
          line = join(",", []string{"Sammy", "Jessica"})
          fmt.Println(line)
      
          line = join(",", []string{"Sammy"})
          fmt.Println(line)
      }
      
      func join(del string, values []string) string {
          var line string
          for i, v := range values {
              line = line + v
              if i != len(values)-1 {
                  line = line + del
              }
          }
          return line
      }
      

      In this program, we are passing a comma (,) as the delimiter to the join function. Then we are passing a slice of values to join. Here is the output:

      Output

      Sammy,Jessica,Drew,Jamie Sammy,Jessica Sammy

      Because the function takes a slice of string as the values parameter, we had to wrap all of our words in a slice when we called the join function. This can make the code difficult to read.

      Now, let’s write the same function, but we’ll use a variadic function:

      join.go

      package main
      
      import "fmt"
      
      func main() {
          var line string
      
          line = join(",", "Sammy", "Jessica", "Drew", "Jamie")
          fmt.Println(line)
      
          line = join(",", "Sammy", "Jessica")
          fmt.Println(line)
      
          line = join(",", "Sammy")
          fmt.Println(line)
      }
      
      func join(del string, values ...string) string {
          var line string
          for i, v := range values {
              line = line + v
              if i != len(values)-1 {
                  line = line + del
              }
          }
          return line
      }
      

      If we run the program, we can see that we get the same output as the previous program:

      Output

      Sammy,Jessica,Drew,Jamie Sammy,Jessica Sammy

      While both versions of the join function do the exact same thing programmatically, the variadic version of the function is much easier to read when it is being called.

      Variadic Argument Order

      You can only have one variadic parameter in a function, and it must be the last parameter defined in the function. Defining parameters in a variadic function in any order other than the last parameter will result in a compilation error:

      join.go

      package main
      
      import "fmt"
      
      func main() {
          var line string
      
          line = join(",", "Sammy", "Jessica", "Drew", "Jamie")
          fmt.Println(line)
      
          line = join(",", "Sammy", "Jessica")
          fmt.Println(line)
      
          line = join(",", "Sammy")
          fmt.Println(line)
      }
      
      func join(values ...string, del string) string {
          var line string
          for i, v := range values {
              line = line + v
              if i != len(values)-1 {
                  line = line + del
              }
          }
          return line
      }
      

      This time we put the values parameter first in the join function. This will cause the following compilation error:

      Output

      ./join_error.go:18:11: syntax error: cannot use ... with non-final parameter values

      When defining any variadic function, only the last parameter can be variadic.

      Exploding Arguments

      So far, we have seen that we can pass zero, one, or more values to a variadic function. However, there will be occasions when we have a slice of values and we want to send them to a variadic function.

      Let’s look at our join function from the last section to see what happens:

      join.go

      package main
      
      import "fmt"
      
      func main() {
          var line string
      
          names := []string{"Sammy", "Jessica", "Drew", "Jamie"}
      
          line = join(",", names)
          fmt.Println(line)
      }
      
      func join(del string, values ...string) string {
          var line string
          for i, v := range values {
              line = line + v
              if i != len(values)-1 {
                  line = line + del
              }
          }
          return line
      }
      

      If we run this program, we will receive a compilation error:

      Output

      ./join-error.go:10:14: cannot use names (type []string) as type string in argument to join

      Even though the variadic function will convert the parameter of values ...string to a slice of strings []string, we can’t pass a slice of strings as the argument. This is because the compiler expects discrete arguments of strings.

      To work around this, we can explode a slice by suffixing it with a set of ellipses (...) and turning it into discrete arguments that will be passed to a variadic function:

      join.go

      package main
      
      import "fmt"
      
      func main() {
          var line string
      
          names := []string{"Sammy", "Jessica", "Drew", "Jamie"}
      
          line = join(",", names...)
          fmt.Println(line)
      }
      
      func join(del string, values ...string) string {
          var line string
          for i, v := range values {
              line = line + v
              if i != len(values)-1 {
                  line = line + del
              }
          }
          return line
      }
      

      This time, when we called the join function, we exploded the names slice by appending ellipses (...).

      This allows the program to now run as expected:

      Output

      Sammy,Jessica,Drew,Jamie

      It’s important to note that we can still pass a zero, one, or more arguments, as well as a slice that we explode. Here is the code passing all the variations that we have seen so far:

      join.go

      package main
      
      import "fmt"
      
      func main() {
          var line string
      
          line = join(",", []string{"Sammy", "Jessica", "Drew", "Jamie"}...)
          fmt.Println(line)
      
          line = join(",", "Sammy", "Jessica", "Drew", "Jamie")
          fmt.Println(line)
      
          line = join(",", "Sammy", "Jessica")
          fmt.Println(line)
      
          line = join(",", "Sammy")
          fmt.Println(line)
      
      }
      
      func join(del string, values ...string) string {
          var line string
          for i, v := range values {
              line = line + v
              if i != len(values)-1 {
                  line = line + del
              }
          }
          return line
      }
      

      Output

      Sammy,Jessica,Drew,Jamie Sammy,Jessica,Drew,Jamie Sammy,Jessica Sammy

      We now know how to pass zero, one, or many arguments, as well as a slice that we explode, to a variadic function.

      Conclusion

      In this tutorial, we have seen how variadic functions can make your code cleaner. While you won’t always need to use them, you may find them useful:

      • If you find that you’re creating a temporary slice just to pass to a function.
      • When the number of input params are unknown or will vary when called.
      • To make your code more readable.

      To learn more about creating and calling functions, you can read How to Define and Call Functions in Go.



      Source link

      How To Define and Call Functions in Go


      Introduction

      A function is a section of code that, once defined, can be reused. Functions are used to make your code easier to understand by breaking it into small, understandable tasks that can be used more than once throughout your program.

      Go ships with a powerful standard library that has many predefined functions. Ones that you are probably already familiar with from the fmt package are:

      • fmt.Println() which will print objects to standard out (most likely your terminal).
      • fmt.Printf() which will allow you to format your printed output.

      Function names include parentheses and may include parameters.

      In this tutorial, we’ll go over how to define your own functions to use in your coding projects.

      Defining a Function

      Let’s start with turning the classic “Hello, World!” program into a function.

      We’ll create a new text file in our text editor of choice, and call the program hello.go. Then, we’ll define the function.

      A function is defined by using the func keyword. This is then followed by a name of your choosing and a set of parentheses that hold any parameters the function will take (they can be empty). The lines of function code are enclosed in curly brackets {}.

      In this case, we’ll define a function named hello():

      hello.go

      func hello() {}
      

      This sets up the initial statement for creating a function.

      From here, we’ll add a second line to provide the instructions for what the function does. In this case, we’ll be printing Hello, World! to the console:

      hello.go

      func hello() {
          fmt.Println("Hello, World!")
      }
      

      Our function is now fully defined, but if we run the program at this point, nothing will happen since we didn’t call the function.

      So, inside of our main() function block, let’s call the function with hello():

      hello.go

      package main
      
      import "fmt"
      
      func main() {
          hello()
      }
      
      func hello() {
          fmt.Println("Hello, World!")
      }
      

      Now, let’s run the program:

      You’ll receive the following output:

      Output

      Hello, World!

      Notice that we also introduced a function called main(). The main() function is a special function that tells the compiler that this is where the program should start. For any program that you want to be executable (a program that can be run from the command line), you will need a main() function. The main() function must appear only once, be in the main() package, and receive and return no arguments. This allows for program execution in any Go program. As per the following example:

      main.go

      package main
      
      import "fmt"
      
      func main() {
          fmt.Println("this is the main section of the program")
      }
      

      Functions can be more complicated than the hello() function we defined. We can use for loops, conditional statements, and more within our function block.

      For example, the following function uses a conditional statement to check if the input for the name variable contains a vowel, then uses a for loop to iterate over the letters in the name string.

      names.go

      package main
      
      import (
          "fmt"
          "strings"
      )
      
      func main() {
          names()
      }
      
      func names() {
          fmt.Println("Enter your name:")
      
          var name string
          fmt.Scanln(&name)
          // Check whether name has a vowel
          for _, v := range strings.ToLower(name) {
              if v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u' {
                  fmt.Println("Your name contains a vowel.")
                  return
              }
          }
          fmt.Println("Your name does not contain a vowel.")
      }
      

      The names() function we define here sets up a name variable with input, and then sets up a conditional statement within a for loop. This shows how code can be organized within a function definition. However, depending on what we intend with our program and how we want to set up our code, we may want to define the conditional statement and the for loop as two separate functions.

      Defining functions within a program makes our code modular and reusable so that we can call the same functions without rewriting them.

      Working with Parameters

      So far we have looked at functions with empty parentheses that do not take arguments, but we can define parameters in function definitions within their parentheses.

      A parameter is a named entity in a function definition, specifying an argument that the function can accept. In Go, you must specify the data type for each parameter.

      Let’s create a program that repeats a word a specified number of times. It will take a string parameter called word and an int parameter called reps for the number of times to repeat the word.

      repeat.go

      package main
      
      import "fmt"
      
      func main() {
          repeat("Sammy", 5)
      }
      
      func repeat(word string, reps int) {
          for i := 0; i < reps; i++ {
              fmt.Print(word)
          }
      }
      

      We passed the value Sammy in for the word parameter, and 5 for the reps parameter. These values correspond with each parameter in the order they were given. The repeat function has a for loop that will iterate the number of times specified by the reps parameter. For each iteration, the value of the word parameter is printed.

      Here is the output of the program:

      Output

      SammySammySammySammySammy

      If you have a set of parameters that are all the same value, you can omit specifying the type each time. Let’s create a small program that takes in parameters x, y, and z that are all int values. We’ll create a function that adds the parameters together in different configurations. The sums of these will be printed by the function. Then we’ll call the function and pass numbers into the function.

      add_numbers.go

      package main
      
      import "fmt"
      
      func main() {
          addNumbers(1, 2, 3)
      }
      
      func addNumbers(x, y, z int) {
          a := x + y
          b := x + z
          c := y + z
          fmt.Println(a, b, c)
      }
      

      When we created the function signature for addNumbers, we did not need to specify the type each time, but only at the end.

      We passed the number 1 in for the x parameter, 2 in for the y parameter, and 3 in for the z parameter. These values correspond with each parameter in the order they are given.

      The program is doing the following math based on the values we passed to the parameters:

      a = 1 + 2
      b = 1 + 3
      c = 2 + 3
      

      The function also prints a, b, and c, and based on this math we would expect a to be equal to 3, b to be 4, and c to be 5. Let’s run the program:

      Output

      3 4 5

      When we pass 1, 2, and 3 as parameters to the addNumbers() function, we receive the expected output.

      Parameters are arguments that are typically defined as variables within function definitions. They can be assigned values when you run the method, passing the arguments into the function.

      Returning a Value

      You can pass a parameter value into a function, and a function can also produce a value.

      A function can produce a value with the return statement, which will exit a function and optionally pass an expression back to the caller. The return data type must be specified as well.

      So far, we have used the fmt.Println() statement instead of the return statement in our functions. Let’s create a program that instead of printing will return a variable.

      In a new text file called double.go, we’ll create a program that doubles the parameter x and returns the variable y. We issue a call to print the result variable, which is formed by running the double() function with 3 passed into it:

      double.go

      package main
      
      import "fmt"
      
      func main() {
          result := double(3)
          fmt.Println(result)
      }
      
      func double(x int) int {
          y := x * 2
          return y
      }
      
      

      We can run the program and see the output:

      Output

      6

      The integer 6 is returned as output, which is what we would expect by multiplying 3 by 2.

      If a function specifies a return, you must provide a return as part of the code. If you do not, you will receive a compilation error.

      We can demonstrate this by commenting out the line with the return statement:

      double.go

      package main
      
      import "fmt"
      
      func main() {
          result := double(3)
          fmt.Println(result)
      }
      
      func double(x int) int {
          y := x * 2
          // return y
      }
      
      

      Now, let’s run the program again:

      Output

      ./double.go:13:1: missing return at end of function

      Without using the return statement here, the program cannot compile.

      Functions exit immediately when they hit a return statement, even if they are not at the end of the function:

      return_loop.go

      package main
      
      import "fmt"
      
      func main() {
          loopFive()
      }
      
      func loopFive() {
          for i := 0; i < 25; i++ {
              fmt.Print(i)
              if i == 5 {
                  // Stop function at i == 5
                  return
              }
          }
          fmt.Println("This line will not execute.")
      }
      

      Here we iterate through a for loop, and tell the loop to run 25 iterations. However, inside the for loop, we have a conditional if statement that checks to see if the value of i is equal to 5. If it is, we issue a return statement. Because we are in the loopFive function, any return at any point in the function will exit the function. As a result, we never get to the last line in this function to print the statement This line will not execute..

      Using the return statement within the for loop ends the function, so the line that is outside of the loop will not run. If, instead, we had used a break statement, only the loop would have exited at that time, and the last fmt.Println() line would run.

      The return statement exits a function, and may return a value if specified in the function signature.

      Returning Multiple Values

      More than one return value can be specified for a function. Let’s examine the repeat.go program and make it return two values. The first will be the repeated value and the second will be an error if the reps parameter is not a value greater than 0:

      repeat.go

      package main
      
      import "fmt"
      
      func main() {
          val, err := repeat("Sammy", -1)
          if err != nil {
              fmt.Println(err)
              return
          }
          fmt.Println(val)
      }
      
      func repeat(word string, reps int) (string, error) {
          if reps <= 0 {
              return "", fmt.Errorf("invalid value of %d provided for reps. value must be greater than 0.", reps)
          }
          var value string
          for i := 0; i < reps; i++ {
              value = value + word
          }
          return value, nil
      }
      

      The first thing the repeat function does is check to see if the reps argument is a valid value. Any value that is not greater than 0 will cause an error. Since we passed in the value of -1, this branch of code will execute. Notice that when we return from the function, we have to provide both the string and error return values. Because the provided arguments resulted in an error, we will pass back a blank string for the first return value, and the error for the second return value.

      In the main() function, we can receive both return values by declaring two new variables, value and err. Because there could be an error in the return, we want to check to see if we received an error before continuing on with our program. In this example, we did receive an error. We print out the error and return out of the main() function to exit the program.

      If there was not an error, we would print out the return value of the function.

      Note: It is considered best practice to only return two or three values. Additionally, you should always return all errors as the last return value from a function.

      Running the program will result in the following output:

      Output

      invalid value of -1 provided for reps. value must be greater than 0.

      In this section we reviewed how we can use the return statement to return multiple values from a function.

      Conclusion

      Functions are code blocks of instructions that perform actions within a program, helping to make our code reusable and modular.

      To learn more about how to make your code more modular, you can read our guide on How To Write Packages in Go.



      Source link