Introduction

Greetings, seeker of knowledge! Today, we're embarking on a journey to navigate the world of Go. We will focus particularly on Go functions — one of the key components in the programming universe.

Just as a recipe guides you through blending ingredients to create a delightful dish, functions in programming accept specific inputs or arguments, process them, and generate an output. For instance, consider a function in a meal-prep app. You input what ingredients you have, the app processes the input, and instantly, you receive a list of recipes you can cook. A striking illustration, isn't it?

Are you ready to start creating your own Go functions? Let's dive in!

Learning to Write Go Functions

So, how do we create a Go function? It's quite straightforward and involves several key components: the func keyword, the function's name, parentheses (), return types, and curly brackets {}. Here's an example:

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

In this example, helloWorld is the name of the function. Within its body, enclosed by curly brackets {}, it performs an operation — printing the phrase "Hello, World!". We invoke or "call" this function using its name followed by parentheses. Let's give it a try:

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

// Call the function
helloWorld() // Prints: "Hello, World!"

When the code above runs, it prints "Hello, World!" on your screen. Congratulations! You've just coded your very first Go function.

Empty Function Body in Go

Unlike Python, Go doesn't have a pass operator to define empty functions. Instead, you can use a TODO comment to signal an as-yet-undefined function in Go.

func notImplementedFunction() {
    // TODO: Implement this.
}

If you attempt to call this function now, it won't do anything because nothing has been defined within its body.

Functions with Arguments

Just as a recipe can vary based on the ingredients used, functions in Go become more versatile as we introduce different arguments. These inputs allow our Go functions to produce varied results.

func greet(message string) {
    fmt.Println(message)
}

// Call the function with "Good Morning!"
greet("Good Morning!") // Prints: "Good Morning!"
// Call the function with "Good Evening!"
greet("Good Evening!") // Prints: "Good Evening!"

Here, the greet function accepts a message argument of type string and prints it. When we use a specific argument, it prints exactly this string. It allows us to execute the same code snippet a bit differently with a short call.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal