C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Type: We use the type keyword before the name of the struct. The Location here is not an instance—it is something we must create with new.
New: In main, we see the syntax for creating an instance of struct type. New() is a built-in function.
X: Finally we assign the "x" field of the struct to a value. Then we read it and display it to the screen.
Golang program that uses struct, new built-in method
package main
import "fmt"
type Location struct {
x int
y int
valid bool
}
func main() {
// Create a new Location struct instance.
loc := new(Location)
// Set a field and then print its value.
loc.x = 10
fmt.Println(loc.x)
}
Output
10
Empty slice: First we create an empty slice of structs. These are pointers—which are variables of a specific type.
Append: We create two Location structs with the new keyword. We use append to add these to our slice.
Finally: We loop over all indexes in our slice. We use fmt.Println to display the struct data to the console.
Golang program that uses slice of structs, pointer types
package main
import "fmt"
type Location struct {
x, y int
valid bool
}
func main() {
// Create empty slice of struct pointers.
places := []*Location{}
// Create struct and append it to the slice.
loc := new(Location)
loc.x = 10
loc.y = 20
loc.valid = true
places = append(places, loc)
// Create another struct.
loc = new(Location)
loc.x = 5
loc.y = 8
loc.valid = true
places = append(places, loc)
// Loop over all indexes in the slice.
// ... Print all struct data.
for i := range(places) {
place := places[i]
fmt.Println("Location:", place)
}
}
Output
Location: &{10 20 true}
Location: &{5 8 true}
First: We create 3 structs and add them all as keys in the "storage" map. The value for each is "true."
Then: We create 2 structs and use them to look up values in the map. We get the correct results.
Golang program that uses structs as map keys
package main
import "fmt"
type Measure struct {
size int
unit string
}
func main() {
// A map with struct keys.
storage := map[Measure]bool{}
// Add 3 structs as keys in the map.
m := new(Measure)
m.size = 10
m.unit = "centimeters"
storage[*m] = true
m = new(Measure)
m.size = 20
m.unit = "feet"
storage[*m] = true
m = new(Measure)
m.size = 10
m.unit = "decibels"
storage[*m] = true
// There are 3 keys in the map.
fmt.Println("Map len", len(storage))
// Create structs to look up values in the map.
key := new(Measure)
key.size = 10
key.unit = "centimeters"
v := storage[*key]
fmt.Println("Result", key, v)
key = new(Measure)
key.size = 100
key.unit = "decibels"
v = storage[*key]
fmt.Println("Result", key, v)
}
Output
Map len 3
Result &{10 centimeters} true
Result &{100 decibels} false