I've a struct called item
type Item struct {
Limit int
Skip int
Fields string
}
item := Item {
Limit: 3,
Skip: 5,
Fields: "Valuie",
}
how could I get the field name, value and join it into a string.
something like:
item := Item {
Limit: 3,
Skip: 5,
Fields: "Valuie",
}
to a string something like
"Limit=3&Skip=5&Fields=Valuie"
And I've try reflections to get convert interface to field value map so far. Am I going the right way? Cause I think there might have some better solutions. And thanks!
m, _ = reflections.Items(data)
for k, v := range m {
fmt.Printf("%s : %s\n", k, v)
}
I've got
Limit : %!s(int=3)
Skip : %!s(int=5)
Fields : Valuie
(Update: to put the output into a string instead of printing it, use str := fmt. Sprintf("%#v", var) . If size matters you can use %v , but I like %#v because it will also include the field names and the name of the struct type. A third variation is %+v which will include the field names, but not the struct type.
Strings are not supported inside structs. Structs don't have vtables so you can't have any variable length or optional fields inside the structs.
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.
You can use %v instead of %s. %s will assume a string, something that can be converted to a string (i.e. byte array) or an object with a String() method. Using %v will check the type and display it correctly.
Example of the String() method call with %s with your example: http://play.golang.org/p/bxE91IaVKj
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With