Welcome to Golang Programs, Get the best new programs in your inbox, daily.

Functions

Each line of code that we create to performs a specific task, and we combine these lines of code to carry out a desired result. Sometimes we desire to repeat the lines of code with different data, and in some actions our code becomes so long that keeping track of what each part does is hard. Functions serve as system tools that keep your code precise and orderly.
A function is a group of statements that exist within a program for the purpose of executing a specific task. In Golang, a function can be called multiple times within the package, and also from other packages if the functions are exported to other packages.

Declaring Functions

Here is the syntax for writing functions in Go:

The first line of a function provides information about what the function will accept as an input and what to expect as an output and this we called as the function signature.

func [function_name] (param1 type, param2 type...) (returned type1, returned type2...) { 
    //Function body 
} 

The func keyword signifies that this is the start point of a function. Next comes the name of the function. Then there is a set of brackets declares the expected variables (a list of parameters) for this function. After that there is closing bracket comes with an optional list of return types. The opening brace signifies the start of the function body, which is wrapped up by the closing bracket between them we write the logic for the function.

  1. Function without return value

    package main
    
    import "fmt"
    
    func main() {
    	add(20, 30)
    }
    
    func add(x int, y int) {
    	total := 0
    	total = x + y
    	fmt.Println(total)
    }
    
    C:\golang\example>go run test1.go
    50

    C:\golang\example>
  2. Function with return value

    In this example, the add() function takes input of two integer numbers and returns a integer value with a name of total.
    package main
    
    import "fmt"
    
    func main() {
    	fmt.Println(add(20, 30))
    }
    
    func add(x int, y int) int {
    	total := 0
    	total = x + y
    	return total
    }
    
    C:\golang\example>go run test1.go
    50

    C:\golang\example>
    The types of input and return value must match with function signature. If we will modify the above program and pass some string value in argument then program will throw an exception "cannot use "test" (type string) as type int in argument to add".
  3. Return types can have names

    We can also name the return value by defining variables, here a variable total of integer type is defined in the function declaration for the value that the function returns.
    package main
    
    import "fmt"
    
    func main() {
    	fmt.Println(add(20, 30))
    }
    
    func add(x int, y int) (total int) {
    	total = x + y
    	return total
    }
    
    C:\golang\example>go run test1.go
    50

    C:\golang\example>