Structs

// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.

Arrays, Slices and Maps deal with a single data type.

A struct is a fixed sized aggregate data type but can hold different data types.

Structs are data types so can be copied like arrays, meaning a copy of a struct is unique.

Define struct#

The following example if how to define and work with a struct directly, notice the struct myPet contains a mix of strings and integer.

main.gogo
package main

import "fmt"

func main() {

    var myPet struct {
		name  string
		breed string
		id    int
	}

	myPet.id = 1
	myPet.name = "Mollie"
	myPet.breed = "Terrier"

	fmt.Println(myPet)
	fmt.Println(myPet.name)
}

Type struct#

A more flexible approach is to define a type struct, which looks a lot like defining a class in Java, were you define a class and can have multiple objects instantiated from that “blue print”.

main.gogo
package main

import "fmt"

func main() {

	type myPet struct {
		name  string
		breed string
		id    int
	}

	dog := myPet{
		id:    1,
		name:  "Mollie",
		breed: "Terrier",
	}

	fmt.Println(dog)

	fish := myPet{
		id:    2,
		name:  "Jelly",
		breed: "Gold",
	}

	fmt.Println(fish)
}

Compare struct#

You can compare structs:

main.gogo
package main

import "fmt"

func main() {

	type myPet struct {
		name  string
		breed string
		id    int
	}

	dog := myPet{
		id:    1,
		name:  "Mollie",
		breed: "Terrier",
	}

	fish := myPet{
		id:    2,
		name:  "Jelly",
		breed: "Gold",
	}

	samePet := dog == fish
	fmt.Println(samePet)
}