Advertisement

In this blog, we will learn about Golang Function, Return Values, anonymous Function and Methods.

Let’s see what we are going to learn in Golang Function, Return Values, Anonymous Function.

  • Basic Syntax of Golang Function
  • Golang Function Parameter
  • Return Values
  • Golang Function multiple return values
  • Functions as Types
  • Golang Anonymous Functions
  • Methods in Golang

Before learning Golang Function, Return Values make sure Basics of Golang are clear:

Golang Functions

Golang Functions Syntax
Golang Function Syntax | Source – Divyanshu Shekhar

Example:

Golang Functions Syntax Example
Golang Function Syntax Example | Source – Divyanshu Shekhar

Golang Functions Naming Convention

The Function names in Golang can either use camelCase or PascalCase:

  • camelCasing – If you want the visibility of the function in the same package.
  • PascalCasing– If you want the visibility of the function outside the package.

Golang Main Function

package main

import (
	"fmt"
)

func main() {

	fmt.Println("Hello GO!")

}

This is a simple example of Go Code. From the First blog itself we are working with functions.

The main is also a function in Golang.

Every Go Program needs an entry point to start the execution of code and the main function in Package main is that entry point that allows us to execute our code.

The main function in Package main takes no parameters and also return no values.

Golang Function Parameters

We have seen how to create a function in Golang, let’s see how we can pass parameters in that function.

1. Golang Functions Single Parameter

package main

import (
	"fmt"
)

func display(message string) {
	fmt.Println(message)
}

func main() {

	fmt.Println("Display Function")
	display("Hello Go")

}

Output:

Display Function
Hello Go

2. Function Multiple Parameter with same Data type

func sum(a int, b int) {
	fmt.Println("The Sum is :", a+b)
}

func main() {

	fmt.Println("Sum Function")
	sum(10, 7)

}

Output:

Sum Function
The Sum is: 17

In this example, both the parameters are of integer type. There’s another way how we can declare parameters.

func sum(a, b int) {
	fmt.Println("The Sum is :", a+b)
}

If all the parameters passed in the function are of the same type, it can also be declared at the last. If a single type is declared in the parameter list, all the parameter values are assumed to have that datatype.

Example:

func sum(message string, a, b int) {
	fmt.Println(message, a+b)
}

func main() {

	fmt.Println("Sum Function")
	sum("The Sum is :", 10, 7)

}

It also gives the same output as above.

In the sum function parameters passed are a message of string type, a and b have int type as a hasn’t got any data type and the last parameter b has got int type and thus a shares the type of b.

Golang Function Parameter Error

func sum(message string, a, b int) {
	fmt.Println(message, a+b)
}

func main() {

	fmt.Println("Sum Function")
	sum(20, 10, 7)

}

The sum function accepts a string and two int parameters, but what if we give an integer value to the string that accepted the argument.

sum(20, 10, 7)

Error:- cannot use 20 (type untyped int) as type string in argument to sum

Golang Call By Value

func display(msg, name string) {
	fmt.Println(msg, name)
	name = "Golang"
	fmt.Println(name)
}

func main() {
	msg := "Hello"
	name := "Go"

	display(msg, name)
	fmt.Println(name)

}

Output:

Hello Go
Golang
Go

In Call by Value, the actual arguments (The arguments that are passed in a function call eg. sum(10,7) ) pass copied value to formal arguments (parameters/arguments in a function declaration), and any changes made in the formal arguments doesn’t affect the actual parameters.

Golang Function Call by Pointers

func display(msg, name *string) {
	fmt.Println(*msg, *name)
	*name = "Golang"
	fmt.Println(*name)
}

func main() {
	msg := "Hello"
	name := "Go"

	display(&msg, &name)
	fmt.Println(name)

}

Output:

Hello Go
Golang
Golang

In Call by Pointers, the actual arguments pass the address to the formal arguments and any change made in the formal arguments also reflects the actual parameters.

Advantages of Golang Functions Call by Pointer:

  • When the argument needs to be changed inside the function.
  • Call by Pointers is efficient, it doesn’t copy the value, simply starts pointing at it.
  • Memory efficient
  • Fast and Good Performance

Golang Function Return Value

Until now, the functions were only used to calculate and display some results, but now the function can also return something.

Example:

func sum(s ...int) int {

	sum := 0

	for _, v := range s {
		sum += v
	}
	return sum
}

func main() {

	s1 := sum(1, 2, 3, 4)
	s2 := sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
	fmt.Println("sum 1 :", s1)
	fmt.Println("sum 2 :", s2)

}

Same Output as above.

Golang Return Pointer

In other languages, returning a pointer is not possible, but in The Go language pointers can also be returned.

Golang return Pointer Syntax:

*

Example:

func sum(s ...int) *int {

	sum := 0

	for _, v := range s {
		sum += v
	}
	return &sum
}

func main() {

	s1 := sum(1, 2, 3, 4)
	s2 := sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
	fmt.Println("Memory address of s1 and s2 :", s1, s2)
	fmt.Println("sum 1 :", *s1)
	fmt.Println("sum 2 :", *s2)

}

Output:

Memory address of s1 and s2 : 0xc0000100a0 0xc0000100a8
sum 1 : 10
sum 2 : 55

In the example, some variable is declared inside the sum function and holds a memory address in the execution stack of the RAM. When the sum function’s execution is over the execution stack is destroyed and so the sum variable. Then how do we get the sum variable’s value.

The Answer is Golang is very intelligent while working with pointers, it promotes the sum variable to the heap memory as the variable shares memory with another variable.

Golang Function Named Return Values

func sum(a, b int) (result int) {
	result = a + b
	return
}

func main() {

	fmt.Println("sum:", sum(10, 7))

}

Output:

sum: 17

In Named Return, the return variable is declared at the return prototype and while returning the variable only the return statement is written without specifying any variable name.

This is actually not used very often in Go code, as the code gets very long it’s difficult to analyze what the function returns, to know that we have to come to the function declaration or signature.

Golang Function Multiple return Values

func sum(a, b int) (string, int) {
	result := a + b
	msg := "sum:"
	return msg, result
}

func main() {
	msg, sum := sum(10, 7)
	fmt.Println(msg, sum)

}

Output:

sum: 17

Practical Example of Golang Function Multiple return values:

package main

import (
	"fmt"
)

func divide(a, b float64) (float64, error) {
	if b == 0.0 {
		return 0.0, fmt.Errorf("Can't Divide by 0")
	}
	return a / b, nil
}

func main() {
	d, err := divide(10.0, 0.0)
	if err != nil {
		fmt.Println(err)
                return
	}
	fmt.Println(d)

}

Output:

when b = 0.0

Can’t Divide by 0

when b = 5.0

2

Golang Functions Undeclared

func main() {

	welcome()

	welcome := func() {
		fmt.Println("Hello World")
	}

	welcome()

}

Error:- undefined: welcome

As the welcome function is not declared and is invoked early, thus an error of undefined function type is received.

Go Methods

Syntax:

func () () { // Body }
type student struct {
	name   string
	rollno int
}

func (s student) details() {
	fmt.Println(s.name, s.rollno)
}

func main() {

	s := student{
		name:   "Divyanshu Shekhar",
		rollno: 17,
	}
	s.details()

}

Output:

Divyanshu Shekhar 17

A Golang Method is like a Golang Function but the difference is that methods only invoke themselves for a known context.

Hope you all liked it!

Read Why Golang is called the future of server-side language?

Learn more about Golang Functions, Anonymous Functions, and Methods from the official Golang Documentation.

About Author
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top