Search⌘ K
AI Features

Solution 1: Reflection and Interfaces

Explore how to implement reflection and interfaces in Go to enable dynamic typing and sorting of data structures. This lesson covers creating custom types with methods for sorting slices and using empty interfaces with type assertions to handle multiple data types within a single function.

Problem 1: Solution

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

Go (1.18.2)
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, which is essentially a slice of a Person structs.

  • Lines 17–19: The Len() method returns the length of the slice. ...