Menu
Coddy logo textTech

Returning a Single Value

Part of the Fundamentals section of Coddy's GO journey — lesson 55 of 109.

Functions can return values to the code that called them. This allows functions to compute results and give them back.

To create a function that returns a value, add the return type after the parameter list:

func multiply(x int, y int) int {
    result := x * y
    return result
}

func main() {
    product := multiply(4, 5)
    fmt.Println("4 × 5 =", product)
}

When you run this program, it outputs:

4 × 5 = 20

The return keyword sends the value back to where the function was called, and the returned value can be stored in a variable.

challenge icon

Challenge

Beginner

In this challenge, you'll practice creating a function that returns a single value. You need to complete the getGreeting function that returns a greeting message based on the time of day.

The function should return "Good morning" if the hour is before 12, "Good afternoon" if the hour is between 12 and 17 (inclusive), and "Good evening" otherwise.

Cheat sheet

Functions can return values using the return keyword. Specify the return type after the parameter list:

func multiply(x int, y int) int {
    result := x * y
    return result
}

func main() {
    product := multiply(4, 5)
    fmt.Println("4 × 5 =", product)
}

The returned value can be stored in a variable or used directly.

Try it yourself

package main

import "fmt"

// getGreeting returns a greeting based on the hour of the day
func getGreeting(hour int) string {
    // TODO: Return "Good morning" if hour is less than 12
    // TODO: Return "Good afternoon" if hour is between 12 and 17 (inclusive)
    // TODO: Return "Good evening" for all other hours
    
    // Your code here
    
}

func main() {
    // Test the function with different hours
    morningHour := 8
    afternoonHour := 15
    eveningHour := 20
    
    fmt.Println("At", morningHour, "hours:", getGreeting(morningHour))
    fmt.Println("At", afternoonHour, "hours:", getGreeting(afternoonHour))
    fmt.Println("At", eveningHour, "hours:", getGreeting(eveningHour))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals