In Go, how can I get the string representation of a struct?

For my application, it does not matter if the string is human readable or not.

Answers


One popular way of encoding structs into strings is using JSON.

You have certain limitations such as not getting all the information (such as the specific type of each field), only serializing exported fields, and not handling recursive values. But it is a simple standard way of serializing data.

Working example:

package main

import (
    "fmt"
    "encoding/json"
)

type s struct {
    Int       int
    String    string
    ByteSlice []byte
}

func main() {
    a := &s{42, "Hello World!", []byte{0,1,2,3,4}}

    out, err := json.Marshal(a)
    if err != nil {
        panic (err)
    }

    fmt.Println(string(out))
}

If it's a "one way" serialization (for debugging or logging or whatever) then fmt.Printf("%#v", var) is very nice. (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.

They are all documented at the top of the fmt documentation.

If you need two-way serialization JSON, Gob or XML are the easiest/built-in options in Go, see the encoding packages.


Need Your Help

Poor performing context menu

windows-phone-7 xaml silverlight-3.0 contextmenu

I'm displaying a simple twitter feed in my app and I have implemented a refresh method in the context menu. Problem is that displaying the context menu performs poorly (it's not a matter of quantit...

Can I use a JavaScript variable within Server-Side Tags?

javascript jquery asp.net

I am trying to pass a JavaScript variable to a server-side tag to avoid a post-back.