首页 > 解决方案 > 如何使用地图中的值

问题描述

我想使用我创建的地图中的值与输入给出的天数相乘。

我只是不知道如何扫描存储在地图中的值。

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.
}

标签: go

解决方案


您可以将用户输入作为字符串获取并针对地图进行测试以检索关联的值。

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")
}

推荐阅读