golang将结构体字符串化(没有数据)

Is there out of the box a golang method that could allow me to stringize (serialize as a string) a go structure.

Serializing with zero values is an option, but an ugly one.

Here is a sample program that uses the encoding/json package to serialize and de-serialze a simple struct. See the code comments for an explaination.

Note that I omit error handling here.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

// your data structure need not be exported, i.e. can have lower case name
// all exported fields will by default be serialized
type person struct {
    Name string
    Age  int
}

func main() {
    writePerson := person{
        Name: "John",
        Age:  32,
    }

    // encode the person as JSON and write it to a bytes buffer (as io.Writer)
    var buffer bytes.Buffer
    _ = json.NewEncoder(&buffer).Encode(writePerson)

    // this is the JSON-encoded text
    // output: {"Name":"John","Age":32}
    fmt.Println(string(buffer.Bytes()))

    // deocde the person, reading from the buffer (as io.Reader)
    var readPerson person
    _ = json.NewDecoder(&buffer).Decode(&readPerson)

    // output: {John 32}
    fmt.Println(readPerson)
}