A struct can bundle attributes together. If you create a struct, you can set a couple of variables for that struct. Those variables can be of any datatype.

A key difference from an array is that elements of an array are all of the same datatype. That is not the case with a struct.

If you want to combine variables, structs are the way to go. Unlike the concept of object oriented programming, they are just data holders.

Struct in golang

Struct example

The golang example creates a new struct. Then it sets the variables.


package main

import "fmt"

type Person struct {
   name string
   job string
}
func main() {
   var aperson Person
    
   aperson.name = "Albert"
   aperson.job = "Professor"
   
   fmt.Printf( "aperson.name =  %s\n", aperson.name)
   fmt.Printf( "aperson.job  =  %s\n", aperson.job)
}

The program bundles the variables (job, name) into a struct named Person.Then that structure can be used to set variables.

In this example the struct has only two variables, but a struct can have as many as you need.

You can create multiple items with the same struct, all with different values. Elements of a struct can be accessed immediately.

Video tutorial

Video tutorial below

Exercises

  1. Create a struct house with variables noRooms, price and city
  2. How does a struct differ from a class?