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:
package main
import (
"fmt"
)
type emp struct {
name string
emp_id int
salary int
}
func main() {
e := emp{ "GFG" , 134, 30000}
fmt.Printf( "%+v" , e)
fmt.Println()
fmt.Printf( "%v" , e)
}
|
Output:
{name:GFG emp_id:134 salary:30000}
{GFG 134 30000}
2. Print using Marshal of package encoding/json.
Example:
package main
import (
"encoding/json"
"fmt"
)
type emp struct {
Name string
Emp_id string
Salary int
}
func main() {
var e = emp{
Name: "GFG" ,
Emp_id: "123" ,
Salary: 78979854 ,
}
jsonF, _ := json.Marshal(e)
fmt.Println(string(jsonF))
}
|
Output:
{"Name":"GFG","Emp_id":"123","Salary":78979854}