Go: Functions

Function Declaration


func function_name( [parameter list] ) [return_types]
   body of the function

The declaration of the function contains:

  • funcIt is a keyword in Go language, which is used to create a function.
  • function_nameIt is the name of the function.
  • Parameter-listIt contains the name and the type of function parameters.
  • Return_type: It is optional and it contains the types of values that function returns. If you are using return_type in your function, then it is necessary to use a return statement in your function.

Function Arguments

Call by value

By default, Go programming language uses call by value method to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function

func swap(int x, int y) int {
   var temp int

   temp = x /* save the value of x */
   x = y    /* put y into x */
   y = temp /* put temp into y */

   return temp;

Call by reference

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. 

func swap(x *int, y *int) {
   var temp int

   temp = *x    /* save the value at address x */
   *x = *y      /* put y into x */
   *y = temp    /* put temp into y */

Leave a Reply

Your email address will not be published. Required fields are marked *