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.
We'll cover the following...
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.
Code explanation
Here’s how the above code works:
Lines 9–12: The
Personstructure is defined with two fields:Name(a string) andAge(an integer).Line 14: Create a custom
personstype, which is essentially a slice of aPersonstructs.Lines 17–19: The
Len()method returns the length of the slice. ...