Solution 1: Reflection and Interfaces
Let’s solve the challenges set in the previous lesson.
We'll cover the following...
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 mainimport ("fmt""sort")// Define a struct typetype Person struct {Name stringAge int}type persons []Person// Implementing sort.Interface - STARTfunc (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 - ENDfunc main() {// Create a slice of Person structspeople := []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 slicefmt.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) andAge
(an integer).Line 14: Create a custom
persons
type, ...