Printing structure variables in console in Golang

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:



{name:GFG emp_id:134 salary:30000}
{GFG 134 30000}

2. Print using Marshal of package encoding/json.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}

chevron_right


Output:

{"Name":"GFG","Emp_id":"123","Salary":78979854}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.