Search⌘ K

Solution 2: Go Packages and Functions

Learn how to effectively develop and manage Go packages and functions. Understand different approaches to sorting integers and the advantages of using named versus unnamed return values in Go functions, enhancing both readability and conciseness.

We'll cover the following...

Solution

Here are the two versions of the function that sorts three int values.

Go (1.18.2)
package main
import (
"fmt"
)
// Function with named return values
func sortInts(a, b, c int) (x, y, z int) {
// Create local variables to store the sorted values
var first, second, third int
// Sort the input values
if a > b {
first, second = b, a
} else {
first, second = a, b
}
if second > c {
second, third = c, second
} else {
third = c
}
// Set the output parameters
x, y, z = first, second, third
return
}
// Function without named return values
func sortInts2(a, b, c int) (int, int, int) {
if a > b {
a, b = b, a
}
if b > c {
b, c = c, b
}
if a > b {
a, b = b, a
}
return a, b, c
}
func main() {
// Testing the function with named return values
x, y, z := sortInts(3, 1, 2)
fmt.Println(x, y, z)
// Testing the function without named return values
a, b, c := sortInts2(5, 4, 6)
fmt.Println(a, b, c)
}

Code explanation

  • Lines 8–29: The sortInts function takes three integer arguments a, b, and c, and returns three integers: x, y, and z. The function first creates three local variables—first, second, and third—to store the sorted values. It then compares a and b, and the smaller ...