Variables

Structs in Go

A struct (structure) stores several variables (fields).


Syntax
type structName struct {
    variableName dataType
}

//accessing a struct field
structName.variableName

Notes

Structs can be used a type when declaring a variable.

Using '_', the name of a variable within a struct can be implicitly specified.

All fields inside of a struct must be uniquely named.

When initializing the struct, the fields can be initialized implicitly (with variables stored in order of declaration) or associatively.


Example
package main

import "fmt"

type car struct {
    make, model string
    year int
}

func main() {
    myCar := car{"Tesla", "Model S", 2014} //implicit declaration
    yourCar := car{make: "Tesla", model: "Model S", year: 2013} //associative
    fmt.Println("My car: ", myCar.make, myCar.model)
}

< Maps   |   If Statement >

© 2018 SyntaxDB. All Rights Reserved.