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
packageMarshal()
functionbyteArr, _ := json.Marshal(structure)
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))}
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.
Printf()
functionWe 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.
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)}
In the output, we can see the fields of the structure along with their names.