Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 147 ยท Functions

Functions

Learn Go functions from the ground up - syntax, parameters and results, grouped types, functions as values, pass-by-value, exported names, and how init and main run.

A function is a named, reusable block of code. You give it some input (parameters), it does some work, and it hands back a result. Every Go program is built from functions, starting with main, and the standard library is mostly functions too.

This lesson introduces the basic syntax, how parameters are passed, the idea that functions are values you can store and pass around, naming and exporting, and the special functions main and init. The following lessons build on it: multiple return values, variadic functions, closures, defer and more.

Declaring and calling a function

A function declaration has the keyword func, a name, a parameter list in parentheses, an optional result type, and a body in braces. Each parameter has a name followed by its type (the type comes after the name in Go).

Go
func name(param1 Type1, param2 Type2) ResultType {
	// body
	return value
}
Go Your first functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A function with a result must end in a return statement that provides a value of that type (or in a statement the compiler can prove never finishes, such as a panic or an endless loop). A function without a result may use a bare return to leave early, or just run off the end.

Grouped parameters

When neighboring parameters share a type, you may write the type once at the end of the group. These two signatures are identical:

Go
func area(width int, height int) int
func area(width, height int) int

Parameters of different types are listed separately, and you can mix both styles: func scale(x, y float64, factor int) float64 groups only x and y.

Go Parameters of different types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Note that area(3, 4.5) compiles even though 3 looks like an integer: the constant 3 is untyped, so it becomes a float64 here. A variable of type int would be rejected (see Operators and Type Conversion and Inference).

The compiler checks calls

Go checks every call against the signature: the number of arguments, their types, and whether a result is used correctly. A missing return or the wrong number of arguments is a compile-time error, not a runtime surprise.

Go Wrong number of arguments (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error shows what you passed and what the function expects:

TEXT
./main.go:10:18: not enough arguments in call to add
	have (number)
	want (int, int)

The second typical mistake is forgetting to return on some path:

Go A missing return (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports ./main.go:11:1: missing return, pointing at the closing brace. The if/else if chain has no final else, so the compiler cannot prove that a value is always returned. Add return "zero" at the end to fix it.

Arguments are passed by value

Go always passes arguments by value: the function receives a copy of each argument. Changing a parameter inside the function does not change the caller's variable.

That sounds simple but has a twist for types that contain references. A slice, map or channel value is a small descriptor that points to shared data, so the copy still refers to the same underlying elements. Compare:

Go Pass by value, and what a copy of a slice shares

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

To let a function change a caller's variable, pass a pointer, as bumpPointer does. Pointers are explained in Pointers, and the rules for slices in How Slices Work.

Functions are values

In Go, functions are first-class values: you can store them in variables, put them in slices and maps, pass them to other functions and return them. A function's type is written like its signature without names, for example func(int, int) int. The zero value of a function variable is nil, and calling a nil function panics.

Go Storing and passing functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Passing functions into functions is the foundation of higher-order functions, and function literals that capture variables are closures. Functions can only be compared with nil, not with each other.

You cannot declare a named function inside another function in Go; use a function literal assigned to a variable instead.

Names, exports and documentation

Go uses capitalization instead of keywords like public and private. A function whose name starts with an uppercase letter is exported and can be called from other packages (fmt.Println, strings.ToUpper). A lowercase name is private to its package. Inside a single package main program this makes no difference, but you will see it everywhere once you split code into packages (Packages and Visibility).

Naming conventions:

  • Use camelCase (or PascalCase when exported), never underscores: parseHeader, ParseHeader.
  • Keep names short in small scopes and precise in large ones. A function in package http is http.Get, not http.HTTPGetRequest: the package name already provides context.
  • Name functions by what they do (a verb: Parse, Close) and boolean-returning ones like questions (IsEmpty, HasPrefix).
  • Document exported functions with a comment that starts with the function name: // Add returns the sum of a and b. Tools such as go doc read these (Comments and Documentation).

main and init

Execution of a Go program starts in func main() of package main. It takes no parameters and returns nothing; when it returns, the program ends, even if other goroutines are still running.

Before main, Go initializes the package: first the package-level variables (in dependency order), then every function named init. An init function also has no parameters and results, you cannot call it yourself, and a package (even a single file) may contain several of them; they run in the order they appear.

Go Initialization order: variables, init, main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output order is both package variables, then init #1, then init #2, then main starts. Use init sparingly: it is for setup that cannot be written as a variable initializer, such as registering a database driver. Hidden work that runs on import makes programs harder to understand and to test.

Keep functions small and focused. If you cannot describe what a function does in one sentence, or if it needs a long list of parameters, it is usually doing too much. Group related parameters into a struct (Structs) or split the function.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which signature is valid Go for a function that takes two ints and returns their product?

    In Go the type follows the name, and neighboring parameters of the same type can share it.
  2. 2. What does this print? func inc(n int) { n++ } called as x := 5; inc(x); fmt.Println(x)

    Arguments are passed by value, so inc increments its own copy. Pass &x and use a *int parameter to change x.
  3. 3. What happens when a function with a result type has a path that ends without a return?

    Go requires that every path ends in a return (or a terminating statement such as panic).
  4. 4. Why does func Add(a, b int) int differ from func add(a, b int) int in a library?

    A name that starts with an uppercase letter is exported from its package; lowercase names are visible only inside the package.
  5. 5. What is the order of execution in a program with package variables, an init function and main?

    Go initializes package-level variables first, then runs init functions, and finally calls main.

Summary

  • Declare functions with func name(params) result { ... }; types come after names, and a, b int shares one type.
  • Every call is checked at compile time for argument count and types, and non-void functions must return on all paths.
  • Arguments are passed by value; pass a pointer to let a function modify the caller's variable. Slices, maps and channels share their underlying data.
  • Functions are values: store them in variables, maps and slices, pass them as arguments, and compare them only with nil.
  • Uppercase names are exported, lowercase names are private.
  • A program initializes package variables, runs init functions, then calls main.

Next: Multiple Return Values and Named Results