Go, Software Development

Three Ways To Declare and Initialize a Struct in Golang

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.

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.

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.

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.

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.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like