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?

huangapple go评论95阅读模式
英文:

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?

问题

这是我的代码:

package main

import "fmt"

var map1 = make(map[string]string)

func main() {
	deleteItem()
}

func deleteItem() {
	fmt.Println("输入要删除的键:")
	var key2 string
	fmt.Scanln(&key2)

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

这是错误信息:

go:95:9: 调用 delete 时参数过多
已有 (map[string]string, string)
需要 ()

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

英文:

This is my code:
package main

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

This is the error message

go:95:9: too many arguments in call to delete
have (map[string]string, string)
want ()

I'm trying to create a map where the program can delete items upon user input but it doesn't seem like I can pass a variable as an argument to the delete() function.
Is there any way to get around this?

答案1

得分: 3

你将函数命名为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)
}
英文:

You named your function delete, so inside it you shadow the builtin delete() function, and using it will refer to your delete() function. Rename it.

Also note that to achieve what you want, you don't need a loop, just use 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)
}

huangapple
  • 本文由 发表于 2022年1月17日 07:34:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/70735091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定