To convert a struct to a string in Go, you can use the “fmt.Sprintf()” function or “marshaling the struct into JSON string format”.
Method 1: Using the fmt.Sprintf() function
The “fmt.Sprintf()” method converts a struct to a string using the function. The “%+v” format specifier is used, which prints the struct with field names, making the output more readable.
Example
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}
In the above code example, we created a Person struct and used the fmt.Sprintf() function with the %+v format specifier converts the struct to a string.
The %+v specifier prints the struct with field names, making it more readable.
Method 2: Marshaling the struct into a json string
This approach involves converting a struct to a JSON string using the “json.Marshal()” function. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. This approach provides a more structured and human-readable format for the struct, making it suitable for data interchange or storage purposes.
Example
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"}
In this code example, we created a Person struct and used the “json.Marshal()” function to convert the struct into a JSON string.
The JSON format is more suitable for data interchange or when you need to store the struct in a human-readable format.
Both approaches have their use cases, and you can select the one that suits your needs better.
The “fmt.Sprintf()” method provides a simple string representation, while the JSON method provides a more structured, human-readable format.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.