登录
首页 >  Golang >  Go问答

提高 Go 中的 Translation Func Map 的键复用性,同时保证性能的高效利用

来源:stackoverflow

时间:2024-02-08 23:18:23 178浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《提高 Go 中的 Translation Func Map 的键复用性,同时保证性能的高效利用》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我想用一个数据结构创建一个 go func,让我输入一个字符串和所需的语言,并得到一个翻译,其中每个翻译都以某种方式与其他翻译连接。

这就是我想要的:

translatekeyword("es-us", "mathe") // output is "matemáticas"
translatekeyword("en-us", "matemáticas") // output is "math"
translatekeyword("de-de", "math") // output is "mathe"

我已经在 go 中创建了一个函数,如果你给出一个英语单词和所需的语言,你就会得到翻译后的输出。

func translateKeyword(lang, keyword string) string {
  keywordDictionary := map[string]map[string]string{
    "home": {
      "en-US": "home",
      "es-US": "inicio",
      "de-DE": "start",
    },
    "about": {
      "en-US": "about",
      "es-US": "conóceme",
      "de-DE": "über",
    },
    // more....
  }

  translation, ok := keywordDictionary[keyword][lang]
  if ok {
    return translation
  }
  return keyword
}
translateKeyword("de-DE", "about") // output is "über" 
translateKeyword("es-US", "über") // output is "über" :(

您还可以在下面放置一个嵌套循环来查找您插入的任何关键字以查找英语单词,然后正常浏览地图。您也可以一遍又一遍地重复按键,以便西班牙语和德语分别成为按键,但必须有比这更好的方法。

我真正想要的是找到一种简单的方法来使任何翻译工作成为关键。我想找到一种方法,而不必在底部创建一个丑陋、低效的循环,或者不必将所有翻译分散开,以防我想轻松添加或删除新的集合。我可以做些什么来让我的生活更轻松?


正确答案


根据您已有的输入,您可以构建您想要的字典,例如:

func build_dict(in map[string]map[string]string) (out map[string]map[string]string) {
    out = make(map[string]map[string]string)
    for _, m := range in {
        for l1, w1 := range m {
            if out[l1] == nil {
                out[l1] = make(map[string]string)
            }
            for _, w2 := range m {
                out[l1][w2] = w1
            }
        }
    }
    return out
}

然后你就可以了

var dictionary = build_dict(map[string]map[string]string{
    "home": {
        "en-us": "home",
        "es-us": "inicio",
        "de-de": "start",
    },
    // ...
})

您的函数可以更新为:

func translatekeyword(lang, kw string) string {
    x, ok := dictionary[lang][kw]
    if ok {
        return x
    }
    return ""
}

https://go.dev/play/p/9iIlAzLpwow

正如您所看到的,build_dict 函数不需要地图中的根键,因此您只需使用一小部分地图即可实现相同的功能,即

[]map[string]string{{
    "en-US": "math",
    "es-US": "matemáticas",
    "de-DE": "mathe",
}, {
    "en-US": "about",
    "es-US": "conóceme",
    "de-DE": "über",
}}

以上就是《提高 Go 中的 Translation Func Map 的键复用性,同时保证性能的高效利用》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>