Start learning free

LESSON 33 OF 671 · FUNCTIONS I

Why Functions in Go

Lesson

Functions help us avoid repeating the same code over and over.

For example, instead of writing these two print statements every time we want to introduce Andy:

func mainFunction() {
    fmt.Println("My name is Andy")
    fmt.Println("I love coding")
}

we can put the repeated code inside a function:

func introduceYourself() {
    fmt.Println("My name is Andy")
    fmt.Println("I love coding")
}

Now every call to introduceYourself() runs those two statements:

func mainFunction() {
    introduceYourself()
    introduceYourself()
}

This keeps code shorter, easier to read, and easier to update.


Assignment
Follow the Coding Tutorial and let's practice using a function more than once.


Hint
Define the function once, then call it wherever you need that behavior.


STEP 1 OF 5
    Ctrl + Enter to check