Struct in Golang is a container type similar to a Java class or Rust struct containing various fields or properties of various data types. All have equivalent ways of creating an instance. This post shows how three ways to declare and initialize a struct in Golang.
How to Define a Struct in Golang
Before we declare and initialize a variable of a struct type, we need first to define a struct type with fields or properties. We can do it using the type keyword as follows.
1 2 3 4 5 6 | // Define Person struct outside of a function type Person struct { lastName string firstName string id int } |
What does the Person struct definition tell us? It tells us that the Person struct can hold two strings and an integer value.
Option 1 – Declare and Initialize a Struct By Passing Arguments
The first option to attain our goal is a bad practice. Consider the following codes.
1 2 3 4 5 | func main() { person := Person{"karl", "san gabriel", 1000} } |
Notice how to treat the struct declaration and initialization. We treat it like a function call, except we use curly braces instead of parentheses. This option is a bad practice because the position of the struct fields can change. Moreover, we could inadvertently add a new field between existing fields. As a result, our code could initialize wrongly or break during compile-time.
Option 2 – Declare and Initialize a Struct in Golang By key-pair values
This second option uses explicit mapping of struct fields with their corresponding values. Consider the following codes.
1 | person := Person{ id: 1000, firstName: "karl", lastName: "san gabriel"} |
For example, we map the field id to the value 1000, firstName to “karl” etc.
Option 3 – Create a Blank Instance of a struct
Finally, we have option 3. This option allows us to declare and initialize an instance of a struct with fields having “zero” values. For example, a field of type string gets an empty (“”) string, an integer initializes to zero, a boolean gets false, etc.
Consider the following codes.
1 2 | var bob Person fmt.Println(bob) |
When we run the codes, we get { 0}.
Do you want to try these codes out in your local machine? You need to install Golang first and probably a decent IDE.