Golang - Working with objects
Table of Contents
How to sort struct fields in alphabetical order?
https://stackoverflow.com/questions/30913483/how-to-sort-struct-fields-in-alphabetical-order
A struct
is an ordered collection of fields. The fmt
package uses reflection to get the fields and values of a struct
value, and generates output in the order in which they were defined.
So the simplest solution would be to declare your type where you already have your fields arranged in alphabetical order:
type T struct {
A int
B int
}
If you can’t modify the order of fields (e.g. memory layout is important), you can implement the Stringer
interface by specifying a String()
method for your struct type:
func (t T) String() string {
return fmt.Sprintf("{%d %d}", t.A, t.B)
}
The fmt
package checks if the passed value implements Stringer
, and if it does, calls its String()
method to generate the output.