json\/encoding<\/strong> package. This also allows pretty print of a struct as well.<\/li><\/ul>\n\n\n\nLet’s say we have an employee struct as below:<\/p>\n\n\n\n
type employee struct {\n name string\n age int\n salary int\n}<\/code><\/pre>\n\n\n\nLet’s see the two ways in which we can print the instance of the employee struct.<\/p>\n\n\n\n
<\/span>Using the fmt package<\/strong><\/span><\/h1>\n\n\n\nfmt.Printf()<\/strong> function can be used to print a struct. Different format identifiers can be used to print a struct in different ways. Let’s see how different format identifiers can be used to print a struct in different formats.<\/p>\n\n\n\nLet’s first create an instance of employee<\/p>\n\n\n\n
emp := employee{name: \"Sam\", age: 31, salary: 2000}<\/code><\/pre>\n\n\n\n%v<\/strong> – It will print only values. Field name will not be printed. This is the default way of printing a struct. Eg<\/li><\/ul>\n\n\n\nfmt.Printf(\"%v\", emp) - {Sam 31 2000}<\/code><\/pre>\n\n\n\n%+v – <\/strong>It will print both field and value. Eg<\/li><\/ul>\n\n\n\nfmt.Printf(\"%+v\", emp) - {name:Sam age:31 salary:2000}<\/code><\/pre>\n\n\n\n%#v – It will print the struct name, also both field and value. Eg<\/li><\/ul>\n\n\n\nfmt.Printf(\"%#v\", emp) - main.employee{name:\"Sam\", age:31, salary:2000}<\/code><\/pre>\n\n\n\nfmt.Println()<\/strong> function can also be used to print a struct. Since %v is the default for fmt.Printlin()<\/strong> function, hence output will be same as using %v for fmt.Printf()<\/strong><\/p>\n\n\n\nfmt.Println(emp) - {Sam 31 2000}<\/code><\/pre>\n\n\n\nLet’s see a working program too<\/p>\n\n\n\n
package main\n\nimport \"fmt\"\n\ntype employee struct {\n name string\n age int\n salary int\n}\n\nfunc main() {\n emp := employee{name: \"Sam\", age: 31, salary: 2000}\n fmt.Printf(\"Emp: %v\\n\", emp)\n fmt.Printf(\"Emp: %+v\\n\", emp)\n fmt.Printf(\"Emp: %#v\\n\", emp)\n fmt.Println(emp)\n}<\/code><\/pre>\n\n\n\nOutput<\/strong><\/p>\n\n\n\nEmp: {Sam 31 2000}\nEmp: {name:Sam age:31 salary:2000}\nEmp: main.employee{name:\"Sam\", age:31, salary:2000}\n{Sam 31 2000}<\/code><\/pre>\n\n\n\n<\/span>Printing the struct in JSON form<\/strong><\/span><\/h1>\n\n\n\nSecond method is to print the struct in the JSON format. Marshal<\/strong> and MarshalIndent<\/strong> function of encoding\/json<\/strong> package can be used to print a struct in JSON format. Here is the difference<\/p>\n\n\n\nMarshal<\/strong> – Below is the signature of the Marshal<\/strong> function. This function returns the JSON encoding of v <\/strong>by traversing the value recursively<\/li><\/ul>\n\n\n\nMarshal(v interface{}) ([]byte, error)<\/code><\/pre>\n\n\n\nMarshalIndent<\/strong>– Below is the signature of the MarshalIndent<\/strong> function. It is similar to Marshal <\/strong>function but applies Indent to format the output. So it can be used to pretty print a struct<\/li><\/ul>\n\n\n\nMarshalIndent(v interface{}, prefix, indent string) ([]byte, error)<\/code><\/pre>\n\n\n\nIt is to be noted that both Marshal<\/strong> and MarshalIndent<\/strong> function can only access the exported fields of a struct, which means that only the capitalized fields can be accessed and encoded in JSON form.<\/p>\n\n\n\npackage main\n\nimport (\n \"encoding\/json\"\n \"fmt\"\n \"log\"\n)\n\ntype employee struct {\n Name string\n Age int\n salary int\n}\n\nfunc main() {\n emp := employee{Name: \"Sam\", Age: 31, salary: 2000}\n \/\/Marshal\n empJSON, err := json.Marshal(emp)\n if err != nil {\n log.Fatalf(err.Error())\n }\n fmt.Printf(\"Marshal funnction output %s\\n\", string(empJSON))\n\n \/\/MarshalIndent\n empJSON, err = json.MarshalIndent(emp, \"\", \" \")\n if err != nil {\n log.Fatalf(err.Error())\n }\n fmt.Printf(\"MarshalIndent funnction output %s\\n\", string(empJSON))\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\nMarshal funnction output {\"Name\":\"Sam\",\"Age\":31}\n\nMarshalIndent funnction output {\n \"Name\": \"Sam\",\n \"Age\": 31\n}<\/code><\/pre>\n\n\n\nThe salary field is not printed in the output because it begins with a lowercase letter and is not exported. The Marshal<\/strong> function output is not formatted while the MarshalIndent<\/strong> function output is formatted.<\/p>\n\n\n\ngolang <\/strong>also allows the JSON encoded struct key name to be different by the use of struct meta fields. Let’s first understand what is struct meta fields. A struct in go also allows adding metadata to its fields. These meta fields can be used to encode decode into different forms, doing some forms of validations on struct fields, etc. So basically any meta information can be stored with fields of a struct and can be used by any package or library for different purposes.<\/p>\n\n\n\nBelow is the format for attaching a meta-data. Meta-data is a string literal i.e it is enclosed in backquotes<\/p>\n\n\n\n
type strutName struct{\n fieldName type `key:value key2:value2`\n}<\/code><\/pre>\n\n\n\nNow for our use case, we will add JSON tags to employee struct as below. Marshal function will use the key name specified in the tags<\/p>\n\n\n\n
type employee struct {\n Name string `json:\"n\"`\n Age int `json:\"a\"`\n Salary int `json:\"s\"`\n}<\/code><\/pre>\n\n\n\nLet’s see full program<\/p>\n\n\n\n
package main\n\nimport (\n \"encoding\/json\"\n \"fmt\"\n \"log\"\n)\n\ntype employee struct {\n Name string `json:\"n\"`\n Age int `json:\"a\"`\n Salary int `json:\"s\"`\n}\n\nfunc main() {\n emp := employee{Name: \"Sam\", Age: 31, Salary: 2000}\n \/\/Converting to jsonn\n empJSON, err := json.MarshalIndent(emp, '', ' ')\n if err != nil {\n log.Fatalf(err.Error())\n }\n fmt.Println(string(empJSON))\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\n{\n \"n\": \"Sam\",\n \"a\": 31,\n \"s\": 2000\n}<\/code><\/pre>\n\n\n\nThe key name in the output is the same as specified in the JSON meta tags.<\/p>\n\n\n\n
Printing nested struct<\/strong><\/p>\n\n\n\nEven if the struct contains another struct , same method as discussed above can be used to print the same<\/p>\n\n\n\n
package main\n\nimport (\n \"encoding\/json\"\n \"fmt\"\n \"log\"\n)\n\ntype address struct {\n City string `json:\"city\"`\n Country string `json:\"country\"`\n}\n\ntype employee struct {\n Name string `json:\"name\"`\n Age int `json:\"age\"`\n Salary int `json:\"salary\"`\n Address address `json:\"address\"`\n}\n\nfunc main() {\n address := address{City: \"some_city\", Country: \"some_country\"}\n emp := employee{Name: \"Sam\", Age: 31, Salary: 2000, Address: address}\n \/\/Converting to json\n empJSON, err := json.MarshalIndent(emp, \"\", \" \")\n if err != nil {\n log.Fatalf(err.Error())\n }\n fmt.Printf(\"MarshalIndent funnction output\\n %s\\n\", string(empJSON))\n}<\/code><\/pre>\n\n\n\nOutput<\/strong><\/p>\n\n\n\nMarshalIndent function output\n {\n \"name\": \"Sam\",\n \"age\": 31,\n \"salary\": 2000,\n \"address\": {\n \"city\": \"some_city\",\n \"country\": \"some_country\"\n }\n}<\/code><\/pre>\n\n\n\nThis is all about printing a struct. I hope you have liked this article. Please share the feedback in the comments.<\/p>\n","protected":false},"excerpt":{"rendered":"
Note: If you are interested in learning Golang, then for that we have a golang comprehensive tutorial series. Do check it out \u2013 Golang Comprehensive Tutorial Series. Now let’s see the current tutorial….<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[3,4,298],"class_list":["post-2229","post","type-post","status-publish","format-standard","hentry","category-tech","tag-go","tag-golang","tag-pretty"],"yoast_head":"\n
Pretty print struct variables in Go (Golang) - Welcome To Golang By Example<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n