Welcome to our comprehensive guide on Go Named Return Values! This tutorial is designed for both beginners and intermediate learners, so let's dive in without any fuss.
Named return values in Go are a powerful feature that allows you to return multiple values from a function using named variables. This can make your code more readable, organized, and easier to maintain.
func calculateArea(width, height float64) (area, perimeter float64) {
area = width * height
perimeter = 2 * (width + height)
return
}In the above example, calculateArea function returns two values: area and perimeter.
A function with named return values has a specific signature:
func FunctionName(arguments ...) (returnType1 name1, returnType2 name2, ...) {
// Function body
return
}FunctionName is the name of the function.arguments are the function's parameters.returnType1, name1, returnType2, name2 are the names of the returned values and their data types.Let's consider a simple example of a function that calculates the average, minimum, and maximum values from an array of numbers:
func stats(numbers []float64) (avg, min, max float64) {
min = numbers[0]
max = numbers[0]
sum := 0.0
for _, number := range numbers {
sum += number
if number < min {
min = number
}
if number > max {
max = number
}
}
avg = sum / float64(len(numbers))
return
}You can use this function like so:
numbers := []float64{3, 5, 2, 7, 1}
avg, min, max := stats(numbers)
fmt.Println("Average:", avg)
fmt.Println("Minimum:", min)
fmt.Println("Maximum:", max)What is the purpose of named return values in Go?
That's it for today! In the next lesson, we'll dive deeper into Go functions and explore other useful features. Keep coding and happy learning! 🚀🎉