This question already has an answer here:
I want to use the values in the map I created to multiply with the days that are given by the input.
I just don't know how to scan for the values that are stored in the map.
package main
import "fmt"
func main() {
typeCar := map[string]int{
"audi": 50,
"volvo": 100,
"tesla": 300,
}
fmt.Print("how many days would you like to rent?: ")
var days int
fmt.Scanf("%d", &days)
fmt.Println("the price is:", typeCar["audi"]*days, "euro")
// "typeCar["audi"]" should be the input of the user instead.
}
</div>
To iterate over a map in go, use the range keyword
for key, value := range typeCar {
//access values here
}
This will give you the key and value of that key in the map.
you can get user input as a string and test it against the map to retrieve the value associated.
package main
import "fmt"
func main() {
typeCar := map[string]int{
"audi": 50,
"volvo": 100,
"tesla": 300,
}
fmt.Print("how many days would you like to rent?: ")
var days int
fmt.Scanf("%d", &days)
// "typeCar["audi"]" should be the input of the user instead.
fmt.Printf("waht type %v ? ", typeCar)
var userInput string
fmt.Scan(&userInput)
tCar, ok := typeCar[userInput]
if !ok {
panic("not a valid car")
}
fmt.Println("the price is:", tCar*days, "euro")
}