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 ofencoding/jsonpackage.Printf()function offmtpackage
The Marshal()function
Syntax
byteArr, _ := json.Marshal(structure)
Syntax of Marshal() function
Example
package main// importing necessary packagesimport ("fmt""encoding/json")// structure whose fields are to be printedtype structure struct {Country stringCapital string}func main() {// initializing structurevar s = structure {Country: "India",Capital: "New Delhi",}// marshalling the structurebyteArr, _ := json.Marshal(s)// typecasting byte array to string// and printing on consolefmt.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 packagesimport ("fmt")// structure whose fields are to be printedtype structure struct {Country stringCapital string}func main() {// initializing structurevar s = structure {Country: "India",Capital: "New Delhi",}// printing the structure on consolefmt.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.