Retrieving specific car models

Report a typo

Dominic is an avid automobile fan who likes street racing. He recently started learning Go and created an in-memory SQLite database with the cars table that stores the specifications of all the cars he has raced against in street races:

cars table

Now he wants to retrieve all Car records from the cars table with a top_speed greater than 300 kilometers per hour and a torque greater or equal than 650 Newton-meter, and then print the records using a for...range loop.

Dominic has already created the Car model struct and written the for...range loop that prints the retrieved records. Your task is to help him write the additional required code to retrieve the records using string conditions.

Write a program in Go
package main

import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
)

type Car struct { // Model for the `cars` table
gorm.Model
Manufacturer string
ModelName string
TopSpeed float64
Horsepower float64
Torque float64
}

// nolint:gomnd // DO NOT delete this comment!
func main() {
db := createDB() // DO NOT delete this line! it creates the in-memory database

var cars []Car
// Write the code to retrieve all `Car` records using string conditions below:
result := ?
if result.Error != nil {
log.Fatalf("cannot retrieve cars: %v", result.Error)
}

// DO NOT delete the for...range loop — it prints the retrieved records!
for _, car := range cars {
fmt.Printf("%-2d | %-26s | %.2f | %.2f\n", car.ID, car.ModelName, car.TopSpeed, car.Torque)
}
}

// DO NOT delete the createDB() function — it is a helper function for creating the in-memory database!
func createDB() *gorm.DB {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
must(err)
must(db.AutoMigrate(&Car{}))
populateDatabase(db)
return db
}

// DO NOT delete the must() function — it is a helper function for error handling!
func must(err error) {
if err != nil {
log.Fatal(err)
}
}
___

Create a free account to access the full topic