In this guide, we will look at how we can declare a structure and various methods of how to print a struct in Go.
Declaring a Struct
We can declare a struct in go using the keyword. We start with the keyword type, followed by the name of the structure and the keyword struct.
The syntax is shown:
We then include fields of the structure inside a pair of curly braces.
The example below creates a simple structure:
type user struct {
Name string
Age int
Employed bool
}
func main() {
}
In the above syntax, we create a structure called user. We then set the fields of various data types.
Struct Instance
After the structure declaration, we need to create an instance of the structure. The example below shows you how to create an instance of the user struct.
The snippet above creates an instance of the user structure called user1.
Print struct
We can print a struct using the Printf method from the fmt package. It provides us with special formatting options to print a struct. Such options include:
Formatting Option | Meaning |
---|---|
%v | Print the value of the variable in the default format |
%+v | Print struct field name and its associated value |
Consider the example code below:
import "fmt"
type user struct {
Name string
Age int
Employed bool
}
func main() {
user1 := user{"Jane Doe", 65, false}
fmt.Printf("%v\n", user1)
fmt.Printf("%+v\n", user1)
fmt.Printf("%d\n", user1.Age)
fmt.Printf("%s\n", user1.Name)
}
Using the printf function, we can fetch all fields in the struct or access individual values for the struct.
The resulting output is as shown:
{Name:Jane Doe Age:65 Employed:false}
65
Jane Doe
Note that the %v formatter prints only the values. If you want to get the field name and the associated value, we use the %+v option.
Print Struct – json.Marshall
The second method you can use to print a struct is to use the Marshal() method from the encoding/json package.
Check our tutorial on JSON marshal and Unmarshall in Go to learn more.
The example below illustrates how to use the Marshal function.
import (
"encoding/json"
"fmt"
)
type user struct {
Name string
Age int
Employed bool
}
func main() {
user1 := user{"Jane Doe", 65, false}
JSON, _ := json.Marshal(user1)
fmt.Println(string(JSON))
}
The function should return the struct fields and values as shown in the output below:
Conclusion
The example below discusses various methods to print a struct, such as the Prinft function and JSON marshal.
Thanks for reading!