如何为结构提供字符串格式?

LiJ*_*ung 4 string struct go

我有一个名为item的结构

type Item struct {
    Limit int
    Skip int
    Fields string
}



item := Item {
            Limit: 3,
            Skip: 5,
            Fields: "Valuie",
    }
Run Code Online (Sandbox Code Playgroud)

我怎么能得到字段名称,值并将其加入一个字符串.

就像是:

item := Item {
            Limit: 3,
            Skip: 5,
            Fields: "Valuie",
    }
Run Code Online (Sandbox Code Playgroud)

一个类似的字符串

"Limit=3&Skip=5&Fields=Valuie"
Run Code Online (Sandbox Code Playgroud)

到目前为止,我尝试使用反射将转换接口转换为字段值映射.我走对了路吗?因为我认为可能有更好的解决方案.谢谢!

m, _ = reflections.Items(data)
for k, v := range m {
    fmt.Printf("%s : %s\n", k, v)
}
Run Code Online (Sandbox Code Playgroud)

我有

Limit : %!s(int=3)
Skip : %!s(int=5)
Fields : Valuie
Run Code Online (Sandbox Code Playgroud)

cre*_*ack 9

您可以使用%v而不是%s.%s将假定一个字符串,可以转换为字符串(即字节数组)或具有String()方法的对象.使用%v将检查类型并正确显示.

使用%s的String()方法调用示例:http://play.golang.org/p/bxE91IaVKj