Start learning free

LESSON 35 OF 671 · FUNCTIONS I

Function Parameters & Arguments in Go

Lesson

So far, the functions we've created execute a fixed task without inputs. Most of the time we want functions to produce different outcomes depending on the values we pass into them.

For example, it would be useful if welcomeUser could print Welcome, Andy! or Welcome, John! depending on the user.


Function parameters:

Parameters allow functions to accept input and use that input inside the function body.

In Go, each parameter needs a name and a type. Here is a function with one string parameter:

func welcomeUser(name string) {
    fmt.Println("Welcome, " + name + "!")
}

Calling with arguments:

When we call the function, the values in the parentheses are called arguments.

func welcomeUser(name string) {
    fmt.Println("Welcome, " + name + "!")
}

func mainFunction() {
    welcomeUser("Andy") // Output: Welcome, Andy!
}

Inside the function, name has the value "Andy" for that call.


Multiple parameters:

A function can take as many parameters as it needs:

func printPerson(name string, age int) {
    fmt.Println(name + ", aged " + strconv.Itoa(age))
}

func mainFunction() {
    printPerson("John", 30) // Output: John, aged 30
    printPerson("Mary", 26) // Output: Mary, aged 26
}

The order of the arguments follows the order of the parameters.


Variables as arguments:

Variables can also be passed as arguments:

func mainFunction() {
    name := "Andy"
    age := 28

    printPerson(name, age)   // Output: Andy, aged 28
    printPerson("Mary", age) // Output: Mary, aged 28
}

Assignment
Follow the Coding Tutorial and let's write some functions with parameters.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check