Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide string formatting for structs?

Tags:

string

struct

go

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
like image 534
LiJung Avatar asked Feb 02 '14 02:02

LiJung


People also ask

How do you change a struct to a string?

(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.

Can structs contain strings?

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.

What is %s in string format?

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.


1 Answers

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

like image 190
creack Avatar answered Oct 29 '22 23:10

creack