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)
fmt.Println("the price is:", typeCar["audi"]*days, "euro")
// "typeCar["audi"]" should be the input of the user instead.
}
解决方案
您可以将用户输入作为字符串获取并针对地图进行测试以检索关联的值。
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")
}
推荐阅读
- java - 我可以创建开放 API 2 文档(通过 swagger),但我无法创建开放 API 3 文档
- ibm-mq - 如何解决 - MQJE001:发生 MQException:完成代码 2,原因 2009
- sql - 比较连续行中的两个值
- powershell - Azure DevOps API:无法反序列化正文值
- r - 基于变量 R 的具有不同形状的散点图
- python - tensorflow.python.framework.errors_impl.NotFoundError:培训/ssd_mobilenet_v2_coco.config;没有这样的文件或目录
- node.js - MongoDB:查询以匹配数组中的每个元素与条件
- javascript - “document.getElementById”如何与“$(this).parent().trigger('submit')”一起运行?
- mysql - mysqld.service 的作业失败,因为控制进程以错误代码退出。帮助 PLS
- c# - 当类型是 C# 9 记录时,FluentAssertions Should().BeEquivalentTo() 在微不足道的情况下失败,似乎将对象视为字符串