Golang struct Tutorial [Practical Examples]


GO

Reviewer: Deepak Prasad

Introduction on Golang struct type

Go structures (structs) are typed collections of fields of different types. In Go you can easily create your custom data type and using struct is one of the ways you can achieve that. The fields declared in the struct type can be both built-in types or custom types. To compose a struct , the fields need to be fixed to a set of unique fields, Therefore Go structs can be considered as templates for creating data records. Go structs are like dictionaries in python and objects in JavaScript.

 

How to declare struct types in golang

To define or declare a struct in Go, start by the keywordtype (denotes creation of a custom type) followed by the struct name and struct keyword (denotes that we are defining a new struct). Let us get started working with structs by creating a main.go file in your working directory and enter the below code.

Example

package main
 
import "fmt"
 
type user struct {
   firstname string
   age       int
   isAwesome bool
   height    float64
}
 
func main() {
   user1 := user{firstname: "John", age: 34, isAwesome: true, height: 5.6}
   fmt.Println("Firstname: ", user1.firstname)
   fmt.Println("Age: ", user1.age)
   fmt.Println("Is Awesome: ", user1.isAwesome)
   fmt.Println("Height: ", user1.height)
}

Output

Firstname:  John
Age:  34
Is Awesome:  true
Height:  5.6

In the above example we have declared a user struct with fields of different types i.e string, int, bool and float64. To create an instance of a struct, define a variable (user1) and initialize it with the user struct and with actual fields with their corresponding values. To get access to the fields of a struct, use the dot notation on the struct instance(user1) for example user1.firstname.

 

Golang struct with Zero value

When you declare a struct without field values, we say that it is a zero value struct. A zero value golang struct has its corresponding field values set to their respective zero value. To define a zero value golang struct , create a variable name and initialize it with the struct name followed by parenthesis e.g user1 := user{}  or use a keyword var followed by the variable name , followed by the struct name e.g var user1 user. Use the dot notation to assign values to the struct fields e.g user1.firstname = "John".

Example

package main
 
import "fmt"
 
type user struct {
   firstname string
   age       int
   isAwesome bool
   height    float64
}
 
func main() {
   user1 := user{}
   var user2 user
 
   fmt.Println(user1)
   fmt.Println(user2)
 
   user1.firstname = "John"
   user1.age = 54
   user1.isAwesome = true
   user1.height = 4.3
 
   fmt.Println(user1)
}

Output

{ 0 false 0}
{ 0 false 0}
{John 54 true 4.3}

 

Declaring a struct using new() function

Golang structs can also be declared using the new() built-in function from the standard library. The new() function creates a new struct and returns a pointer to the struct.  To get access to the fields data, use the dot notation.  To get access to the struct value , dereference the struct using the * (dereferencing) operator as shown below.

Example

package main
 
import "fmt"
 
type user struct {
   firstname string
   age       int
   isAwesome bool
   height    float64
}
 
func main() {
   user1 := new(user)
   fmt.Println(user1)
 
   user1.firstname = "John"
   user1.age = 54
   user1.isAwesome = true
   user1.height = 4.3
  
   fmt.Println(*user1)
   fmt.Println(user1)
}

Output

&{ 0 false 0}
{John 54 true 4.3}
&{John 54 true 4.3}

 

Go anonymous structs

Anonymous golang struct is a struct that does not have a name. They are used to define ephemeral structs for one time use  hence they cannot be referenced anywhere in the code base.

Example

package main
 
import (
   "encoding/json"
   "fmt"
   "log"
)
 
func main() {
   user := struct {
       Firstname string  `json:"firstname"`
       Email     string  `json:"email"`
       IsAwesome bool    `json:"is_awesome"`
       Height    float64 `json:"height"`
   }{
       Firstname: "john",
       Email:     "johndoe@golinuxcloud.com",
       IsAwesome: true,
       Height:    5.5,
   }
   response, err := json.Marshal(user)
   if err != nil {
       log.Fatalf("Error: %v", err)
   }
   fmt.Println(string(response))
}

Output

{"firstname":"john","email":"johndoe@golinuxcloud.com","is_awesome":true,"height":5.5}

 

Go Embeded structs

Structs in Go can have other structs nested in them. This is useful when creating complex data models that have relationships. To nest a golang struct inside another struct, one of the fields in the parent struct will be used to connect with the child struct. The child struct is an example of a custom type defining field data in  a struct. In our example , we define user{} and contact{} structs, user{} struct is the parent struct while contact{} is the child struct linked with the contactDetails field.

Example

package main
 
import "fmt"
 
type contact struct {
   phone  int
   email  string
   street string
}
 
type user struct {
   firstname      string
   age            int
   isAwesome      bool
   height         float64
   contactDetails contact
}
 
func main() {
       contact1 := contact{
       phone:  3242323224,
       email:  "johndoe@golinuxcloud.com",
       street: "4th Go street",
   }
    user1 := user{
       firstname:      "John",
       age:            34,
       isAwesome:      true,
       height:         5.6,
       contactDetails: contact1,
   }
 
   fmt.Println(user1)
   fmt.Println(user1.contactDetails)
   fmt.Println(user1.contactDetails.phone)
   fmt.Println(user1.contactDetails.email)
   fmt.Println(user1.contactDetails.street)
}

Output

{John 34 true 5.6 {3242323224 johndoe@golinux.com 4th Go street}}
{3242323224 johndoe@golinux.com 4th Go street}
3242323224
johndoe@golinux.com
4th Go street

 

In an embedded/nested golang struct instance, the fields for the embedded structs can be promoted such that they can be accessed from the parent struct instance without going through the child struct.

Exanple

package main
 
import "fmt"
 
type contact struct {
   phone  int
   email  string
   street string
}
 
type user struct {
   firstname string
   age       int
   isAwesome bool
   height    float64
   contact
}
 
func main() {
   u := user{
       firstname: "John",
       age:       34,
       isAwesome: true,
       height:    5.6,
       contact: contact{
           phone:  3242323224,
           email:  "johndoe@golinuxcloud.com",
           street: "4th Go street",
       },
   }
 
   fmt.Println("User struct: ", u)
   fmt.Println("Firstname: ", u.firstname)
   fmt.Println("Age: ", u.age)
   fmt.Println("Is awesome:", u.isAwesome)
   fmt.Println("Height: ", u.height)
   fmt.Println("Phone:", u.phone)
   fmt.Println("Email:", u.email)
   fmt.Println("Street: ", u.street)
}

Output

User struct: {John 34 true 5.6 {3242323224 johndoe@golinuxcloud.com 4th Go street}}
Firstname: John
Age: 34
Is awesome: true
Height: 5.6
Phone: 3242323224
Email: johndoe@golinuxcloud.com
Street: 4th Go street

 

Go struct tags

Tags in Golang structs are small pieces of metadata attached to fields of a struct that provide instruction to other Go code that interact with the struct. Go struct tags appear after the type in the Go struct declaration , enclosed in backticks ` `. Each tag is composed of key and  corresponding value(s). In Go we use the JSON encoder that defines how names should appear in JSON output. To encode and decode json we will use the encoding/json package.

Example

package main
 
import (
   "encoding/json"
   "fmt"
   "log"
)
 
type User struct {
   Username  string  `json:"firstname"`
   Email     string  `json:"email"`
   IsAwesome bool    `json:"is_awesome"`
   Height    float64 `json:"height"`
}
 
func main() {
   user1 := User{
       Username:  "JohnDoe",
       Email:     "johndoe@gmail.com",
       IsAwesome: true,
       Height:    5.5,
   }
   fmt.Println("User without tagging ", user1)
 
   response, err := json.Marshal(user1)
   if err != nil {
       log.Fatalf("Error: %v", err)
   }
 
   fmt.Println("User with tagging ", string(response))
}

Output

User without tagging  {JohnDoe johndoe@gmail.com true 5.5}
User with tagging  {"firstname":"JohnDoe","email":"johndoe@gmail.com","is_awesome":true,"height":5.5}

 

Go struct with methods

We can add behavior to our golang structs using methods. Methods are function that define or compose the behavior of a struct instance. In order to create a method, function definition will have struct receivers. Receivers in Go are like the self in Python or this in JavaScript .

Example

package main
 
import (
   "encoding/json"
   "fmt"
   "log"
)
 
type User struct {
   Username  string  `json:"firstname"`
   Email     string  `json:"email"`
   IsAwesome bool    `json:"is_awesome"`
   Height    float64 `json:"height"`
}
 
func (u User) userInfo() {
   response, err := json.Marshal(u)
   if err != nil {
       log.Fatalf("Error: %v", err)
   }
 
   fmt.Println(string(response))
}
 
func (u *User) changeEmail(email string) {
   u.Email = email
}
 
func main() {
   user1 := User{
       Username:  "JohnDoe",
       Email:     "johndoe@gmail.com",
       IsAwesome: true,
       Height:    5.5,
   }
   user1.userInfo()
   user1.changeEmail("johndoe@golinuxcloud.com")
   user1.userInfo()
}

Output

{"firstname":"JohnDoe","email":"johndoe@gmail.com","is_awesome":true,"height":5.5}
{"firstname":"JohnDoe","email":"johndoe@golinuxcloud.com","is_awesome":true,"height":5.5}

 

Summary

Golang struct are a very important type in Go, because they give developers flexibility in composing their own custom types and actually make the struct do something using struct methods. Struct enables developers to model real world objects such as employees, users and many more. In this article we have learnt about Go struct declaration, struct zero value, field tagging in structs, struct methods that show how to use structs in our programs.

 

Further Reading

Go by Example: Structs

 

Antony Shikubu

Antony Shikubu

He is highly skilled software developer with expertise in Python, Golang, and AWS cloud services. Skilled in building scalable solutions, he specializes in Django, Flask, Pandas, and NumPy for web apps and data processing, ensuring robust and maintainable code for diverse projects. You can reach out to him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment