Skip to content

Functions in Go

A function is a block of code that’s assigned a name, and contains some instructions.

In the “Hello, World!” example we created a main function, which is the entry point of the program.

package main

import "fmt"

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

That’s a special function.

Usually we define functions with a custom name:

func doSomething() {

}

and then you can call them, like this:

doSomething()

A function can accept parameters, and we have to set the type of the parameters like this:

func doSomething(a int, b int) {

}

doSomething(1, 2)

a and b are the names we associate to the parameters internally to the function.

A function can return a value, like this:

func sumTwoNumbers(a int, b int) int {
	return a + b
}

result := sumTwoNumbers(1, 2)

Note we specified the return value type

A function in Go can return more than one value:

func performOperations(a int, b int) (int, int) {
	return a + b, a - b
}

sum, diff := performOperations(1, 2)

It’s interesting because many languages only allow one return value.

Any variable defined inside the function is local to the function.

A function can also accept an unlimited number of parameters, and in this case we call it variadic function:

func sumNumbers(numbers ...int) int {
	sum := 0
	for _, number := range numbers {
		sum += number
	}
	return sum
}

total := sumNumbers(1, 2, 3, 4)
→ Download my free Go Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about go: