LESSON · 1 OF 23

What a function is

What a function is

A function is a named block of code you can call with inputs and get a result back. You have been calling functions all along - fmt.Println, strings.Contains. Now you write your own.

The basic shape

go
func greet(name string) string {
    return "hello, " + name
}

Read it left to right: func starts the definition, greet is the name, (name string) is the parameter list, and the string after the parentheses is the return type. Inside, return sends a value back to whoever called the function.

Calling it

You run a function by writing its name and passing arguments:

go
message := greet("web-01")   // "hello, web-01"

The value that comes back is what you assigned to message.

Breaking logic into small, named functions is how you keep a program readable, and a function is the unit you will test later.

The shape to memorise

  • func name(params) returnType { } defines a function
  • return sends a value back
  • you call it as name(args)
Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute