How to print struct variables data in Golang?
Last Updated :
22 Jun, 2020
A struct (Structure) is a user-defined type in Golang that contains a collection of named fields/properties which creates own data types by combining one or more types. Also, this concept is generally compared with the classes in object-oriented programming. A struct has different fields of the same or different data types and is declared by composing a fixed set of unique fields.
Syntax:
type StructName struct {
field1 fieldType1
field2 fieldType2
}
struct variables:
variable_name := structure_variable_type {value1, value2...valuen}
There are two ways to print Struct Variables in Golang. The first way is to use the Printf function of package fmt with special tags in the arguments the printing format arguments. Some of those arguments are as below:
%v the value in a default format
%+v the plus flag adds field names
%#v a Go-syntax representation of the value
Example 1:
package main
import (
"fmt"
)
type Employee struct {
Name string
Age int
Salary int
}
func main() {
var e Employee
e.Name = "Simran"
e.Age = 23
e.Salary = 30000
fmt.Printf( "%s\n" , e.Name)
fmt.Printf( "%d\n" , e.Age)
fmt.Printf( "%d\n" , e.Salary)
fmt.Printf( "%#v\n" , e)
}
|
Output:
Simran
23
30000
main.Employee{Name:"Simran", Age:23, Salary:30000}
Example 2:
package main
import "fmt"
type Mobiles struct {
company string
price int
mobile_id int
}
func main() {
var Mobile1 Mobiles
var Mobile2 Mobiles
Mobile1.company = "Vivo"
Mobile1.price = 20000
Mobile1.mobile_id = 1695206
Mobile2.company = "Motorola"
Mobile2.price = 25000
Mobile2.mobile_id = 2625215
fmt.Printf( "Mobile 1 company : %s\n" , Mobile1.company)
fmt.Printf( "Mobile 1 price : %d\n" , Mobile1.price)
fmt.Printf( "Mobile 1 mobile_id : %d\n" , Mobile1.mobile_id)
fmt.Printf( "Mobile 2 company : %s\n" , Mobile2.company)
fmt.Printf( "Mobile 2 price : %d\n" , Mobile2.price)
fmt.Printf( "Mobile 2 mobile_id : %d\n" , Mobile2.mobile_id)
}
|
Output:
Mobile 1 company : Vivo
Mobile 1 price : 20000
Mobile 1 mobile_id : 1695206
Mobile 2 company : Motorola
Mobile 2 price : 25000
Mobile 2 mobile_id : 2625215
To know about this, you can refer to this article.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...