Computer scienceProgramming languagesGolangWorking with dataSerialization and encryption

Serializing structured YAML

An appropriate struct to deserialize cars

Report a typo

You have been provided with an incomplete Go program designed to take a YAML string as input. The program's objective is to deserialize the YAML object into a variable of type Car.

The Car type contains additional struct types, Engine, which encapsulates details about the car's engine, including its type, power, and whether it has a turbocharger. The type Car is declared as follows:

type Engine struct {
	Type  string
	Power int
	Turbo bool
}

type Car struct {
	Make   string
	Model  string
	Year   int
	Price  float32
	Engine Engine
}

The provided YAML string for the input resembles the following example:

make: Tesla
model: model3
year: 2022
price_in_USD: 35999.99
engine_type: V6
max_horsepower: 450
turbo: true

Your task is to write the additional missing code in the program to:

  • Adding the correct YAML struct tags to each field of the Car struct.

  • Implement the necessary code to unmarshal the YAML input string into a variable of type Car.

  • Display the variable holding the unmarshalled YAML input on the standard output.

Sample Input 1:

make: Tesla
model: model3
year: 2022
price_in_USD: 35999.99
engine_type: V6
max_horsepower: 450
turbo: false

Sample Output 1:

{Make:Tesla Model:model3 Year:2022 Price:35999.99 Engine:{Type:V6 Power:450 Turbo:false}}
Write a program in Go
package main

import (
"bufio"
"fmt"
"log"
"os"
"strconv"

"gopkg.in/yaml.v3"
)

// Please replace '?' with the appropriate struct tags
type Engine struct {
Type string `?:"?"`
Power int `?:"?"`
Turbo bool `?:"?"`
}

// Please replace '?' with the appropriate struct tags
type Car struct {
Make string `?:"?"`
Model string `?:"?"`
Year int `?:"?"`
Price float32 `?:"?"`
Engine Engine `?:"?"`
}

func main() {
// DO NOT delete the code block below! - It takes as an input the full YAML object from the test cases
scanner := bufio.NewScanner(os.Stdin)
var carYAML string
for scanner.Scan() {
carYAML += scanner.Text() + "\n"
}

// Write your code here. Please replace '?' with the appropriate code
var car Car
err := ? // unmarshal `carYAML` into the variable `car` of type `Car`
if err != nil {
log.Fatal(err)
}

// Print the unmarshalled object below -- DO NOT change the "%+v" verb!
fmt.Printf("%+v", ?) // Please replace '?' with the apprpriate variable
}
___

Create a free account to access the full topic