How to Convert Struct to String in Golang

To convert a struct to a string in Go, you can “use the fmt.Sprintf() function or marshaling the struct into JSON string format”.

Diagram of Converting Struct to String in Golang

Method 1: Using the fmt.Sprintf() function

The fmt.Sprintf() method converts a struct to a string using the format specifier. The “%+v” format specifier prints the struct with field names, making the output more readable.

package main

import "fmt"

type Person struct {
  Name string
  Age int
  Gender string
}

func main() {
  person := Person{Name: "Krunal", Age: 30, Gender: "male"}

  // Convert the struct to a string using fmt.Sprintf
  personString := fmt.Sprintf("%+v", person)
    fmt.Println(personString)
}

Output

{Name:Krunal Age:30 Gender:male}

Method 2: Marshaling the struct into a json string

This approach involves converting a struct to a JSON string using the “json.Marshal()” function. This approach provides a more structured and human-readable format for the struct, making it suitable for data interchange or storage purposes.

package main

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

type Person struct {
  Name string `json:"name"`
  Age int `json:"age"`
  Gender string `json:"gender"`
}

func main() {
  person := Person{Name: "Krunal", Age: 30, Gender: "male"}

  // Marshal the struct into JSON format
  jsonBytes, err := json.Marshal(person)
  if err != nil {
    log.Fatalf("Error marshaling struct: %v", err)
  }

  // Convert the JSON bytes to a string
  personString := string(jsonBytes)
  fmt.Println(personString)
}

Output

{"name":"Krunal","age":30,"gender":"male"}

Summary Table

Approach Method Description Example Output
Using fmt.Sprintf() fmt.Sprintf() with format verb %+v Converts a struct to a string with field names {Name:Krunal Age:30}
Marshaling into JSON json.Marshal() from encoding/json package Converts a struct into a JSON string format {"name":"Krunal","age":30}

That’s it!