Skip to content

Instantly share code, notes, and snippets.

@jtarang
Last active March 18, 2019 17:59
Show Gist options
  • Save jtarang/e33021c89d3445364478f10c4239562d to your computer and use it in GitHub Desktop.
Save jtarang/e33021c89d3445364478f10c4239562d to your computer and use it in GitHub Desktop.
Go excercise compare cars
package main
import "fmt"
type CarSpecs struct {
horsepower int
torque int
}
type Car struct {
make string
model string
price int
specifications CarSpecs
}
func createCar(make, model string, price, horsepower, torque int) Car {
_car := Car{}
_carSpecs := CarSpecs{}
_car.make, _car.model, _car.price = make, model, price
_carSpecs.horsepower, _carSpecs.torque = horsepower, torque
_car.specifications = _carSpecs
return _car
}
func createCarsArray() []Car {
var _cars []Car
bmwM3 := createCar("BMW", "M3", 75000, 453, 410)
supra := createCar("Toyota", "Supra", 50000, 335, 315)
gsf := createCar("Lexus", "GS F", 85000, 467, 389)
e63s := createCar("Mercedes", "E63s", 130000, 603, 627)
_cars = append(_cars, bmwM3, supra, gsf, e63s)
return _cars
}
func returnMostExpensiveCar(_carList []Car) Car {
_expensiveCar := Car{}
for _carIndex := range _carList {
car := _carList[_carIndex]
// check if empty struct
if _expensiveCar == (Car{}) {
_expensiveCar = car
}
if car.price > _expensiveCar.price {
_expensiveCar = car
}
}
return _expensiveCar
}
func returnCarWithMostHorsepower(_carList []Car) Car {
_horsepowerCar := Car{}
for _carIndex := range _carList {
car := _carList[_carIndex]
// check if empty struct
if _horsepowerCar == (Car{}) {
_horsepowerCar = car
}
if car.specifications.horsepower > _horsepowerCar.specifications.horsepower {
_horsepowerCar = car
}
}
return _horsepowerCar
}
func main() {
cars := createCarsArray()
expensiveCar := returnMostExpensiveCar(cars)
mostHorsepowercar := returnCarWithMostHorsepower(cars)
if expensiveCar == mostHorsepowercar {
fmt.Println("This car is awesome! Buy this one: ", expensiveCar.make, expensiveCar.model)
} else if expensiveCar != mostHorsepowercar {
fmt.Println("Take your pick")
fmt.Println("Most Horsepower: ", mostHorsepowercar.make, mostHorsepowercar.model)
fmt.Println("Most Expensive: ", expensiveCar.make, expensiveCar.model)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment