A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming. It can be termed as a lightweight class that does not support inheritance but supports composition. There are two ways to print struct variables on the console as follows:
1. Using the Printf function with the following tags
%v the value in a default format
%+v the plus flag adds field names
%#v a Go-syntax representation of the value
Example:
// Golang program to show how to print // the struct variables in console package main // importing package for printing import ( "fmt"
) // taking a struct type emp struct {
name string
emp_id int
salary int
} func main() { // an instance of emp (in 'e')
e := emp{ "GFG" , 134, 30000}
// printing with variable name
fmt.Printf( "%+v" , e)
fmt.Println()
// printing without variable name
fmt.Printf( "%v" , e)
} |
Output:
{name:GFG emp_id:134 salary:30000} {GFG 134 30000}
2. Print using Marshal of package encoding/json.
Example:
// Golang program to show how to print // the struct variables in console package main import ( "encoding/json"
"fmt"
) // taking a struct type emp struct {
Name string
Emp_id string
Salary int
} func main() { // an instance of emp (in 'e')
var e = emp{
Name: "GFG" ,
Emp_id: "123" ,
Salary: 78979854 ,
}
// Marshalling the structure
// For now ignoring error
// but you should handle
// the error in above function
jsonF, _ := json.Marshal(e)
// typecasting byte array to string
fmt.Println(string(jsonF))
} |
Output:
{"Name":"GFG","Emp_id":"123","Salary":78979854}