0
0
Goprogramming~15 mins

Named return values in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Named return values
📖 Scenario: Imagine you are writing a small program to calculate the area and perimeter of a rectangle. You want to create a function that returns both values clearly and simply.
🎯 Goal: Build a Go function that uses named return values to return the area and perimeter of a rectangle given its width and height.
📋 What You'll Learn
Create a function called rectangleMetrics that takes two float64 parameters: width and height.
Use named return values area and perimeter of type float64 in the function signature.
Calculate the area as width * height and perimeter as 2 * (width + height) inside the function.
Return the named values without explicitly listing them in the return statement.
Print the returned area and perimeter values in the main function.
💡 Why This Matters
🌍 Real World
Named return values are useful in real-world Go programs where functions return multiple results, like calculations or data processing.
💼 Career
Understanding named return values helps you write clean, readable Go code, a valuable skill for backend development and system programming jobs.
Progress0 / 4 steps
1
Create the main function and call rectangleMetrics
Write a main function that calls a function named rectangleMetrics with width 5.0 and height 3.0, and stores the results in variables area and perimeter.
Go
Hint

Use area, perimeter := rectangleMetrics(5.0, 3.0) inside main.

2
Define rectangleMetrics with named return values
Define a function called rectangleMetrics that takes two float64 parameters named width and height. Use named return values area and perimeter of type float64 in the function signature.
Go
Hint

Write func rectangleMetrics(width, height float64) (area float64, perimeter float64) to declare named return values.

3
Calculate area and perimeter inside rectangleMetrics
Inside the rectangleMetrics function, calculate area as width * height and perimeter as 2 * (width + height). Assign these values to the named return variables.
Go
Hint

Assign area = width * height and perimeter = 2 * (width + height) before return.

4
Print the area and perimeter in main
In the main function, add import "fmt" at the top and print the area and perimeter values using fmt.Println with the exact text: "Area:", area and "Perimeter:", perimeter.
Go
Hint

Use fmt.Println("Area:", area) and fmt.Println("Perimeter:", perimeter) to print the results.