Golang Print Struct Variables [SOLVED]


GOLANG Solutions, GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

In the previous article, we discussed some examples of working with struct in Go. In today's post, I will give you some ways to print out the struct using fmt or some other packages

 

Different methods to print struct variable to console in GO

Method 1: Using fmt package

fmt: Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

func Printf(format string, a ...any) (n int, err error): Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.

fmt package has some verbs as described below:

%v	the value in a default format
	when printing structs, the plus flag (%+v) adds field names
%#v	a Go-syntax representation of the value
%T	a Go-syntax representation of the type of the value
%%	a literal percent sign; consumes no value

Here's an example of using Printf() with %v verb to print out the struct:

package main

import "fmt"

type Person struct {
	id          int
	name        string
	phoneNumber string
}

func main() {
	p1 := Person{
		id:          1,
		name:        "Anna",
		phoneNumber: "+125639842",
	}

	p2 := Person{
		id:          2,
		name:        "Daniel",
		phoneNumber: "+8496587469",
	}

	fmt.Printf("Person 1 info: %+v\n", p1)
	fmt.Printf("Person 2 info: %+v\n", p2)
}

Output:

Person 1 info: {id:1 name:Anna phoneNumber:+125639842}
Person 2 info: {id:2 name:Daniel phoneNumber:+8496587469}

 

Method 2: Using json package

We have some articles about convert between Golang struct and json object.  The below example demonstrate how to use MarshalIndent() in json package to print the struct in a pretty format:

func MarshalIndent(v any, prefix, indent string) ([]byte, error): MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Id          int
	Name        string
	PhoneNumber string
}

func main() {
	p1 := Person{
		Id:          1,
		Name:        "Anna",
		PhoneNumber: "+125639842",
	}

	p2 := Person{
		Id:          2,
		Name:        "Daniel",
		PhoneNumber: "+8496587469",
	}

	prettyStruct(p1)
	fmt.Println("----")
	prettyStruct(p2)
}

func prettyStruct(intef interface{}) {
	output, _ := json.MarshalIndent(intef, "", "\t")
	fmt.Printf("%s \n", output)
}

Output:

{
        "Id": 1,
        "Name": "Anna",
        "PhoneNumber": "+125639842"
}
----
{
        "Id": 2,
        "Name": "Daniel",
        "PhoneNumber": "+8496587469"
}

Note that the fields in struct must be capitalized so that it can be exported.

 

Method 2: Using go-spew package

Go-spew implements a deep pretty printer for Go data structures to aid in debugging. If you're interested in reading about how this package came to life and some of the challenges involved in providing a deep pretty printer, there is a blog post about it at web.archive.org

To install the package:

go get -u github.com/davecgh/go-spew/spew

Here is an example of using Dump() function to print out the struct:

package main

import (
	"github.com/davecgh/go-spew/spew"
)

type Person struct {
	Id          int
	Name        string
	PhoneNumber string
}

func main() {
	p1 := Person{
		Id:          1,
		Name:        "Anna",
		PhoneNumber: "+125639842",
	}

	p2 := Person{
		Id:          2,
		Name:        "Daniel",
		PhoneNumber: "+8496587469",
	}

	spew.Dump(p1)
	spew.Dump(p2)
}

Output:

(main.Person) {
 Id: (int) 1,
 Name: (string) (len=4) "Anna",
 PhoneNumber: (string) (len=10) "+125639842"
}
(main.Person) {
 Id: (int) 2,
 Name: (string) (len=6) "Daniel",
 PhoneNumber: (string) (len=11) "+8496587469"
}

 

Method 4: Implement a custom ToString() function for a struct

It would be better to implement a custom stringer if you want some kind of formatted output of a struct. Here is an example of how to define a ToString() function for a struct:

package main

import (
	"fmt"
)

type Person struct {
	Id          int
	Name        string
	PhoneNumber string
}

func main() {
	p1 := Person{
		Id:          1,
		Name:        "Anna",
		PhoneNumber: "+125639842",
	}

	p2 := Person{
		Id:          2,
		Name:        "Daniel",
		PhoneNumber: "+8496587469",
	}

	p1.toString()
	fmt.Println("-----")
	p2.toString()
}

func (p Person) toString() {
	fmt.Printf(`
	Person id is:     			%d,
	Person name is:   			%s,
	Person phone number is: 	%s
	`, p.Id, p.Name, p.PhoneNumber)
}

Output:

        Person id is:                           1,
        Person name is:                         Anna,
        Person phone number is:         +125639842
        -----

        Person id is:                           2,
        Person name is:                         Daniel,
        Person phone number is:         +8496587469

 

Summary

In this article, I have given 4 examples using different packages to print out the struct to the console. Besides using the built-in packages, we can custom a ToString() function so that we can format the output of a struct.

 

References

https://pkg.go.dev/fmt#Printf
https://go.dev/blog/json

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment