...

/

Solution 1: Reflection and Interfaces

Solution 1: Reflection and Interfaces

Let’s solve the challenges set in the previous lesson.

Problem 1: Solution

This is a Go program that demonstrates sorting a slice of structures based on one of the fields of the structure.

Press + to interact
package main
import (
"fmt"
"sort"
)
// Define a struct type
type Person struct {
Name string
Age int
}
type persons []Person
// Implementing sort.Interface - START
func (p persons) Len() int {
return len(p)
}
func (p persons) Less(i, j int) bool {
return p[i].Age < p[j].Age
}
func (p persons) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
// Implementing sort.Interface - END
func main() {
// Create a slice of Person structs
people := []Person{
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
{"Dave", 35},
}
// Sort the slice using the sorting criteria defined for "persons"
sort.Sort(persons(people))
// Print the sorted slice
fmt.Println(people)
}

Code explanation

Here’s how the above code works:

  • Lines 9–12: The Person structure is defined with two fields: Name (a string) and Age (an integer).

  • Line 14: Create a custom persons type, ...