golang methods are reusable code blocks. By calling a golang method, all of the code in the method will be executed.

Methods should start with a lowercase character and only contain alphabetic characters. A method can take one or more parameters which can be used in the code block.

Methods in golang

Example

The method below can be called as many times as you want: a method is reusable code. Methods can also return output, this output can then be used in the program.


package main

import "fmt"

func main() {
   hello("go")
   hello("")
}


func hello(x1 string) {
   fmt.Printf( "Hello %s", x1);
}

The method hello above is called with a parameter and without. Sometimes parameters are necessary for your codeblock, but at times they are not.

The parameter in this example is x1, which is given a value outside the method.

Return valule

A value inside a golang method only exists there (local scope). It can be given to the program with the return statement, return x1. That then needs to be saved in an output variable.


package main

import "fmt"

func main() {
   var a float64 = 3
   var b float64 = 9
   var ret = multiply(a, b)
   fmt.Printf( "Value is : %.2f", ret )
}

func multiply(num1, num2 float64) float64 {
   var result float64
   result = num1 * num2
   return result 
}

Video tutorial

Video tutorial below:

Exercises

  1. Create a method that sums two numbers
  2. Create a method that calls another method.