【问题标题】:Can you delete keys from a map in Golang using a variable that contains the name of the key instead of the key in quotations?您可以使用包含键名而不是引号中的键的变量从 Golang 中的地图中删除键吗?
【发布时间】:2022-01-16 23:34:20
【问题描述】:

这是我的代码: 主包

import "fmt"

var map1 = make(map[string]string)

func main() {

delete()

}

func delete() {

fmt.Println("Enter key to be deleted: ")
var key2 string
fmt.Scanln(&key2)

fmt.Println(map1)
for index, element := range map1 {
    if index == key2 {

        delete(map1, index)
        fmt.Println(map1)
    
    }
}
}

这是错误信息

go:95:9: 调用中的参数太多要删除 有(地图[字符串]字符串,字符串) 想要()

我正在尝试创建一个地图,程序可以在其中根据用户输入删除项目,但我似乎无法将变量作为参数传递给 delete() 函数。 有没有办法解决这个问题?

【问题讨论】:

  • 重命名你的函数。
  • 不要在你的程序中使用预定义的函数名作为删除。惊讶 go 如何允许它而不在 delete() 抛出错误

标签: dictionary go


【解决方案1】:

你将你的函数命名为delete,所以在它里面你隐藏了内置的delete()函数,并且使用它会引用你的delete()函数。重命名。

还要注意,要实现你想要的,你不需要循环,只需使用delete(map1, key2)

func remove() {
    fmt.Println("Enter key to be deleted: ")
    var key2 string
    fmt.Scanln(&key2)

    fmt.Println(map1)
    delete(map1, key2)
    fmt.Println(map1)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    相关资源
    最近更新 更多