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

golang struct to string json
golang struct tostring
golang print nested struct
struct to string c++
golang convert struct to map
struct to string - matlab
golang fmt
golang return struct

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

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 (

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)


Give this output:

{"Int":42,"String":"Hello World!","ByteSlice":"AAECAwQ="}

String representations for Go values, Or if appropriate encode to JSON and use that. For large data structures it can make debugging easier because you can inspect the output with for example jq. Declaring a struct type. A struct type is nothing but a schema containing the blueprint of a data a structure will hold. To make things simple, we need to create a new derived type so that we can

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.

How convert / print struct as a string : golang, Below is a short example to print or display the struct variables data in console. You can Print Regular expression to extract numbers from a string in Golang. To define a new struct type, you list the names and types of each field. The default zero value of a struct has all its fields zeroed. You can access individual fields with dot notation. 2 ways to create and initialize a new struct. The new keyword can be used to create a new struct. It returns a pointer to the newly created struct.

you can also add a function with that struct receiver.

// URL : Sitemap Xml
type URL struct {
    Loc string `xml:"loc"`

// URLSET : Sitemap XML
type URLSET struct {
    URLS []URL `xml:"url"`

// converting the struct to String format. 
func (u URL) String() string {
    return fmt.Sprintf(u.Loc)

So printing this struct field will return a string.


How to print struct variables in Golang, During the definition of a struct type, optional string values may be added to each field declaration. Find Type of Struct in Go Programming Language. Answer: In your case you don't want to append the string representation of the struct Link, you just need its Href field which is already of type string. func (s Entry) LinkString() string { return s.Link.Href } Also note that if you use a non-pointer receiver Entry, your method LinkString() will receive a copy of the struct.

Attaching a String() function to a named struct allows us to convert a struct to a string.

package main

import "fmt"

type foo struct {
    bar string

func (f foo) String() string {
    return fmt.Sprintf("Foo Says: %s",

func main() {
    fmt.Println(foo{"Hello World!"})
Foo Says: Hello World!

How to convert struct to JSON in Golang, In fact, the same technique can be used to get a string representation of any data structure. var x interface{} = []int{1, 2, 3} str := fmt.Sprintf("%v", x) fmt.Println(str)  In your case you don't want to append the string representation of the struct Link, you just need its Href field which is already of type string. func (s Entry) LinkString() string { return s.Link.Href } Also note that if you use a non-pointer receiver Entry, your method LinkString() will receive a copy of the struct. Which in this case is not a problem, it's just a little slower because a copy has to be made.

Using json or fmt.Sprintf, I make a benchmark,

BenchmarkStructJson-8            1000000          1773 ns/op
BenchmarkStructSprintSharp-8      200000          6139 ns/op
BenchmarkStructSprint-8           500000          2763 ns/op
BenchmarkStructSprintPlus-8       300000          4373 ns/op

BenchmarkStructJson is using json.Marshal @Matheus Santana

BenchmarkStructSprintSharp: `fmt.Sprintf("%#v", &a) @Ask Bjørn Hansen

BenchmarkStructSprint: `fmt.Sprintf("%v", &a)

BenchmarkStructSprintPlus: `fmt.Sprintf("%+v", &a)

The result is, json.Marshal is better performance.

Convert interface to string · YourBasic Go, type point struct { x, y int }. func main() {. Go offers several printing “verbs” designed to format general Go values. For example, this prints an instance of our point  Interfaces as an idiomatic way of abstraction. If you need a generic type in Go - use interface with no doubt. Also you are very close to a correct approach: you don't need to evaluate a struct from string instead of it you should declare a map of object of Converter interface types with all required implementations.

String Formatting, A struct or structure can be compared with the class in the Object-Oriented Programming paradigm. Hence string will have zero value of "" (can't be printed), int will have zero Printf function and %T format syntax, we get the following result. You can use it like this: string statusCode = ResponseStatusCode.SUCCESS; // Automatically converts to string when needed ResponseStatusCode codeByValueOf = ResponseStatusCode.ValueOf(statusCode); // Returns null if not found // Implements TypeConverter so you can use it with string conversion methods.

Structures in Go (structs) - RunGo, A structure or struct in Golang is a user-defined type that allows to Note: We can also make them compact by combining the various fields of the same type as city string. Pincode int. } func main() {. // Declaring a variable of a `struct` type. So, if you have a []byte and need a string then (at least if you’re me), you’d perhaps think the Go compiler would just create a new string structure, set data to point to the data from the []byte and set the length. You might not expect the compiler to allocate a new piece of memory and copy the data over.

Structures in Golang, The horizontal ellipsis … is also used elsewhere in the spec to A comment cannot start inside a rune or string literal, or inside a comment. A floating-point literal is a decimal or hexadecimal representation of a floating-point constant. Structured variables of array, slice, and struct types have elements  In the Slice section I have used your method above to build a representation of the first []subsstruct but of course it is no longer a struct and I cannot process it as one. From the f.Interface() I can get a string that is a json representation of this first level.

  • Are you trying to serialize a struct? You should really use gob for that.
  • Exactly what I needed! +1 to you
  • I noticed you second question and what purpose you have. JSON can be useful, but not if the output string is to be used to create a hash to test equality. You will have problems with maps, as Ask mentioned. This goes for using fmt.Sprintf as well.
  • Didn't know that keys have to be capitalized in order to be show in JSON.
  • Thanks for your response. I should have probably specified in my question that I'm looking to get the value in my program, not the console. In particular, I would like to then convert the string into a byte array. When I do "[]byte(fmt.Printf("%v", var))", the program complains about "multiple-value fmt.Printf() in single-value context". I'm assuming this is because Printf does not return the string value, but only prints it to the console. Do you know of a way to fix this.
  • I figured out how to do this using ANisus's response, but +1 to you for a good answer.
  • If you need it in the program use fmt.Sprintf instead of Printf. If you use JSON, beware that map values might not be returned in the same order on each run (though that might be the case for the fmt printf, too, I haven't checked).