Open In App

How to print struct variables data in Golang?

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:




// Go program to print struct variables data
package main
  
import (
    "fmt"
)
  
// Creating a structure
type Employee struct {
    Name   string
    Age    int
    Salary int
}
  
// Main function
func main() {
    // Creating variables
    // of Employee structure
    var e Employee
    e.Name = "Simran"
    e.Age = 23
    e.Salary = 30000
  
    // Print variable name, value and type
    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:




// Go program to print struct variables data
package main
  
import "fmt"
  
type Mobiles struct {
    company   string
    price     int
    mobile_id int
}
  
func main() {
  
    // Declare Mobile1 of type Mobile
    var Mobile1 Mobiles
      
    // Declare Mobile2 of type Mobile
    var Mobile2 Mobiles
  
    // Mobile 1 specification
    Mobile1.company = "Vivo"
    Mobile1.price = 20000
    Mobile1.mobile_id = 1695206
   
    // Mobile 2 specification
    Mobile2.company = "Motorola"
    Mobile2.price = 25000
    Mobile2.mobile_id = 2625215
  
    // print Mobile1 info
    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)
  
    // print Mobile2 info
    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.


Article Tags :