How to print the structure's fields with their names in Golang

Overview

In Golang, we can print the structure’s fields with their names using the following:

  • Marshal() function of encoding/json package.
  • Printf() function of fmt package

The Marshal()function

Syntax

byteArr, _ := json.Marshal(structure)
Syntax of Marshal() function

Example

package main
// importing necessary packages
import (
"fmt"
"encoding/json"
)
// structure whose fields are to be printed
type structure struct {
Country string
Capital string
}
func main() {
// initializing structure
var s = structure {
Country: "India",
Capital: "New Delhi",
}
// marshalling the structure
byteArr, _ := json.Marshal(s)
// typecasting byte array to string
// and printing on console
fmt.Println(string(byteArr))
}

Explanation

  • Line 4–8: We import the necessary packages.
  • Line 10–13: We create a structure.
  • Line 18–20: We initialize the structure.
  • Line 23: We marshal the structure.
  • Line 27: We typecast the byte array into a string and print it on the console.

Output

The Marshal function will return a byte array. After typecasting it to string, we can see the fields of the structure along with their names on the console.

The Printf()function

We can use the formatted I/O feature of the Printf() function to print the structure's fields along with their names using the %+v argument.

Example

package main
// importing necessary packages
import (
"fmt"
)
// structure whose fields are to be printed
type structure struct {
Country string
Capital string
}
func main() {
// initializing structure
var s = structure {
Country: "India",
Capital: "New Delhi",
}
// printing the structure on console
fmt.Printf("%+v", s)
}

Explanation

  • Line 4–6: We import the necessary packages.
  • Line 9–12: We create a structure.
  • Line 16–19: We initialize the structure.
  • Line 22: We print the structure on the console.

Output

In the output, we can see the fields of the structure along with their names.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources