notexOPENOverview
Notex/Languages/Declaring and Calling Functions
03.01LESSON 01 OF 18 · 2 MIN READ

Declaring and Calling Functions

Always free to read

The basics of Go functions are familiar to anyone who has programmed in other languages with first-class functions, like C, Python, Ruby, or JavaScript. Just as with control structures, Go adds its own twist on function features. Some are improvements, and others are experiments that should be avoided. I’ll cover both in this topic.

You’ve already seen functions being declared and used. Every Go program starts from a main function, and you’ve been calling the fmt.Println function to print to the screen. Since a main function doesn’t take in parameters or return values, let’s see what it looks like when a function does:

func div(num int, denom int) int {
    if denom == 0 {
        return 0
    }
    return num / denom
}

Let’s look at all the new things in this code sample. A function declaration has four parts: the keyword func, the name of the function, the input parameters, and the return type. The input parameters are listed in parentheses, separated by commas, with the parameter name first and the type second. Go is a typed language, so you must specify the types of the parameters. The return type is written between the input parameter’s closing parenthesis and the opening brace for the function body.

Just like other languages, Go has a return keyword for returning values from a function. If a function returns a value, you must supply a return. If a function returns nothing, a return statement is not needed at the end, unless you are exiting from the function before the last line.

The main function has no input parameters or return values. When a function has no input parameters, use empty parentheses (()). When a function returns nothing, you write nothing between the input parameter’s closing parenthesis and the opening brace for the function body:

func main() {
    result := div(5, 2)
    fmt.Println(result)
}

The code for this simple program is in the examples/simple_div directory.

Calling a function should be familiar to you as an experienced developer. On the right side of the :=, you call the div function with the values 5 and 2. On the left side, you assign the returned value to the variable result.

Tip

When you have two or more consecutive input parameters of the same type, you can specify the type once for all of them like this:

func div(num, denom int) int {
Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K