Printing Struct Variables in Golang
Suppose, we need to print the structure with its fields corresponding value. We can do this with the help of package fmt which implements formatted I/O with functions analogous to C’s printf and scanf. Let’s first try if we just print the structure, what will happen.
Go
package main
import ("fmt")
type Fields struct {
Name string
NickName string
Age int
}
func main() {
var f = Fields{
Name: "Abc",
NickName: "abc",
Age: 19 ,
}
fmt.Println(f)
}
|
Output:
{Abc abc 19}
There are two ways to print Struct Variables in Golang. The first way is to use 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
Go
package main
import (
"fmt"
)
type Fields struct {
Name string
NickName string
Age int
}
func main() {
var f = Fields{
Name: "Abc",
NickName: "abc",
Age: 19 ,
}
fmt.Printf("%v\n", f)
fmt.Printf("%+v\n", f)
fmt.Printf("%#v\n", f)
}
|
Output:
{Abc abc 19}
{Name:Abc NickName:abc Age:19}
main.Fields{Name:"Abc", NickName:"abc", Age:19}
Printf with #v includes main.Fields that is the structure’s name. It includes “main” to distinguish the structure present in different packages. Second possible way is to use function Marshal of package encoding/json. Syntax :
func Marshal(v interface{}) ([]byte, error)
Go
package main
import (
"encoding/json"
"fmt"
)
type Fields struct {
Name string
NickName string
Age int
}
func main() {
var f = Fields{
Name: "Abc",
NickName: "abc",
Age: 19 ,
}
jsonF, _ := json.Marshal(f)
fmt.Println( string (jsonF))
}
|
Output:
{"Name":"Abc", "NickName":"abc", "Age":19}
Last Updated :
09 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...