dictionary - 我如何在 Go 中获取 map 的任何给定元素?

标签 dictionary go

假设我有一个 map[string]int,我想要长度最短(以字节为单位)的 key 。如果我不知道 map 包含的任何特定元素,我如何获取它的样本以便我可以做

var shortest string
for key, _ := range myMap {
    if len(key) < len(shortest) {
        shortest = key
    }
}

最佳答案

您可以使用 for 循环并立即跳出它以仅对一个元素进行采样。

var shortest string
for key, _ := range myMap {
    shortest = key
    break
}
for key, _ := range myMap {
    if len(key) < len(shortest) {
        shortest = key
    }
}

丑陋,但它有效。

关于dictionary - 我如何在 Go 中获取 map 的任何给定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36606717/

相关文章:

python - 'str'对象不支持python中的项目分配错误

oracle - 在找不到 Oracle 数据库客户端库时避免 Go panic

mongodb - 如何使用 golang 验证查询 mongodb 中的时间

go - 在 Go 中查找结构的底层匿名字段类型

python - 将嵌套字典转换为字符串

python - 在 Python 中处理数字类型缺失的键

python - 将列表转换为字典,列表项作为键,列表索引作为 python 中的值

python - Elasticsearch (Elasticsearch Curator) Python API。获取 ES 索引及其大小的字典

http - 禁用公用名验证 - Go HTTP 客户端

http - 使用 auth 访问 http 代理