英文:
Why the map doesn't return its value?
问题
我有一个函数,它只是返回一个映射的值。但是由于某些原因它没有这样做。你有什么想法为什么会这样?我在这里粘贴了代码。你也可以使用Try it!来运行它。
package main
import "fmt"
func main() {
a := CountryCode("Australia")
fmt.Println(a)
}
func CountryCode(s string) string {
m := make(map[string]string)
// [snip]
m["AU"] = "Australia"
// [snip]
return m[s]
}
func CodeByCountry(s string) string {
m := make(map[string]string)
// [snip]
m["Australia"] = "AU"
// [snip]
return m[s]
}
英文:
I have a function which simply returns the value of a map. However for some reasons it doesn't do that.
Any idea why ? I've pasted here the code. You may also play it using
package main
import "fmt"
func main() {
a := CountryCode("Australia")
fmt.Println(a)
}
func CountryCode(s string) string {
m := make(map[string]string)
// [snip]
m["AU"] = "Australia"
// [snip]
return m展开收缩
}
func CodeByCountry(s string) string {
m := make(map[string]string)
// [snip]
m["Australia"] = "AU"
// [snip]
return m展开收缩
}
答案1
得分: 9
你没有使用正确的函数,应该使用以名称为键的映射函数。你可能想要使用:
a := CodeByCountry("Australia")
这样可以正常工作。
但是每次需要使用映射时都创建映射是没有意义的。将映射的创建移出函数,例如放在 init 中:
package main
import "fmt"
var byCode = make(map[string]string)
var byName = make(map[string]string)
func init() {
m := byCode
m["AF"] = "Afghanistan"
m["AL"] = "Albania"
m["DZ"] = "Algeria"
m["AS"] = "American Samoa"
m = byName
m["Austria"] = "AT"
m["Mozambique"] = "MZ"
m["Solomon Islands"] = "SB"
m["United States"] = "US"
m["Anguilla"] = "AI"
m["Australia"] = "AU"
}
func CountryCode(s string) string {
return byCode展开收缩
}
func CodeByCountry(s string) string {
return byName展开收缩
}
func main() {
a := CodeByCountry("Australia")
fmt.Println(a)
}
另一种初始化的解决方案是,由于它似乎是双射的,可以有一个函数同时向两个映射中添加一对键值对:
func addInMaps(code, name string) {
byCode[code] = name
byName[name] = code
}
英文:
You're not using the right function, the one using the map whose key is a name. You probably want
a := CodeByCountry("Australia")
This works.
But it makes no sense to create the map each time you need it. Take the map creation out of the functions, and put it for example in the init :
package main
import "fmt"
var byCode = make(map[string]string)
var byName = make(map[string]string)
func init() {
m := byCode
m["AF"] = "Afghanistan"
m["AL"] = "Albania"
m["DZ"] = "Algeria"
m["AS"] = "American Samoa"
m = byName
m["Austria"] = "AT"
m["Mozambique"] = "MZ"
m["Solomon Islands"] = "SB"
m["United States"] = "US"
m["Anguilla"] = "AI"
m["Australia"] = "AU"
}
func CountryCode(s string) string {
return byCode展开收缩
}
func CodeByCountry(s string) string {
return byName展开收缩
}
func main() {
a := CodeByCountry("Australia")
fmt.Println(a)
}
Another solution for the initialization, as it seems bijective, would be to have one function adding a pair and filling both maps :
func addInMaps(code,name string) {
byCode[code] = name
byName[name] = code
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论