2
\$\begingroup\$

I looked for a way to order one interface by key in Golang and print the concatenated values. Because I couldn't find any solution I will share mine. Please feel free to share a better solution.

Imagine that we have a struct and we want to print the values ordered by key.

type Point struct {
    X string
    Y string
    A string
    C string
}

var result interface{} = Point{"1", "2", "4", "5"}

The expected result should be 4512

My solution is:

func sortStructures(structure interface{}) string {
    var result string
    v := reflect.ValueOf(structure)

    //Add all the key of a struct to a array
    values := make([]string, v.NumField())
    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Type().Field(i).Name
    }

    //Sort the keys of the structure
    sort.Strings(values)

    //Concat the values of the ordered keys
    for j := 0; j < len(values); j++ {
        result += v.FieldByName(values[j]).String()
    }

    return result
}

Please note the in my case I needed to get the concatenated string of the values, but I think that with this example you can modify and use for other outputs.

I would like to ask if there is a more efficient way to do it?

Example: Go Play

\$\endgroup\$
  • 2
    \$\begingroup\$ Here you can find a proper answer to your post, with IMHO a better solution. \$\endgroup\$ – Mario Santini Nov 28 '17 at 9:30
  • \$\begingroup\$ Wouldn't you always know what exported fields you have, since go is pretty strongly typed? \$\endgroup\$ – biosckon Dec 4 '17 at 7:13
  • \$\begingroup\$ @biosckon the function sortStructures accepts interfaces, so accepts all kind of structures. I needed this function to order independently of the structure. \$\endgroup\$ – user2249271 Dec 4 '17 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.