Golang Code Examples

Map of Car Options

22 Jul 2014

Description

This example demonstrates how to initialize a set of Car structs:

type Car struct {
    Make  string
    Model  string
    Options []string
}

Each Car has a Make, Model and a slice of Options.

Next, we create a map to associate Options, such as "Allow Wheels", with each car:

car_options := make(map[string][]*Car)
}

We iterate over the Car structs using the range keyword in order to populate the map, thereby associating the current car with it's Options.

Finally, we illustrate various methods of manipulating the map of Options for reporting purposes.


Golang Features

This golang code sample demonstrates the following go language features:

  • map of slices
  • initializing slices
  • iterating ranges
  • pointers
  • struct
  • string package

Code Example

package main

import (
    "fmt"
    "strings"
)

type Car struct {
    Make  string
    Model  string
    Options []string
}

func main() {

    dashes := strings.Repeat("-", 50)

    is250 := &Car{"Lexus", "IS250", []string{"GPS", "Alloy Wheels", "Roof Rack", "Power Outlets", "Heated Seats"}}
    accord := &Car{"Honda", "Accord", []string{"Alloy Wheels", "Roof Rack"}}
    blazer := &Car{"Chevy", "Blazer", []string{"GPS", "Roof Rack", "Power Outlets"}}

    cars := []*Car{is250, accord, blazer}
    fmt.Printf("Cars:\n%v\n\n", cars)  // cars is a slice of pointers to our three cars

    // Create a map to associate options with each car
    car_options := make(map[string][]*Car)

    fmt.Printf("CARS:\n%s\n", dashes)
    for _, car := range cars {
        fmt.Printf("%v\n", car)
        for _, option := range car.Options {
            // Associate this car with each of it's options
            car_options[option] = append(car_options[option], car)
            fmt.Printf("car_options[option]: %s\n", option)
        }
        fmt.Println(dashes)
    }
    fmt.Println(dashes)

    // Print a list of cars with the "GPS" option
    for _, p := range car_options["GPS"] {
        fmt.Println(p.Make, "has GPS.")
    }

    fmt.Println("")
    fmt.Println(len(car_options["Alloy Wheels"]), "has Alloy Wheels.")
}

Notes

We could have associated each car with each of it's options as follows:

car_options["GPS"] = []*Car{is250, blazer}
car_options["Alloy Wheels"] = []*Car{is250, accord, blazer}
car_options["Roof Rack"] = []*Car{is250, accord}
car_options["Power Outlets"] = []*Car{is250, blazer}
car_options["Heated Seats"] = []*Car{is250}

Appending to a nil slice as follows ...

go car_options[option] = append(car_options[option], car)

... just allocates a new slice, so it's a one-liner to append a value to a map of slices; there's no need to check if the key exists.


Output

/usr/local/Cellar/go/1.2.2/libexec/bin/go run /Users/lex/dev/go/samples/src/bitbucket.org/l3x/list/cars.go
Cars:
[0x21025b0c0 0x21025b100 0x21025b140]

CARS:
--------------------------------------------------
&{Lexus IS250 [GPS Alloy Wheels Roof Rack Power Outlets Heated Seats]}
car_options[option]: GPS
car_options[option]: Alloy Wheels
car_options[option]: Roof Rack
car_options[option]: Power Outlets
car_options[option]: Heated Seats
--------------------------------------------------
&{Honda Accord [Alloy Wheels Roof Rack]}
car_options[option]: Alloy Wheels
car_options[option]: Roof Rack
--------------------------------------------------
&{Chevy Blazer [GPS Roof Rack Power Outlets]}
car_options[option]: GPS
car_options[option]: Roof Rack
car_options[option]: Power Outlets
--------------------------------------------------
--------------------------------------------------
Lexus has GPS.
Chevy has GPS.

2 has Alloy Wheels.

Process finished with exit code 0

References

comments powered by Disqus
The content of this site is licensed under the Creative Commons 3.0License and code is licensed under a BSD license