douhan5853 2019-08-26 14:24
浏览 111
已采纳

使用其他变量中的数据引用go中的变量?

I am relatively new to go/ coding.I want to be able to reference a variable by using a variable.

var a = make([]int,0)
var b = make([]int,0)
var c = make([]int,0)

I have some slices defined

set := input.Ask("Which set would you like to input to (a, b, c):")
for true {
  num := input.Ask("Number:")
  strings.toLower(set) = append(strings.toLower(set), num)
}

I want the "strings.tolower" part output a string, which it does, that will allow me to select one of the variables I have defined.

  • 写回答

2条回答 默认 最新

  • dtgu21994537 2019-08-26 15:37
    关注

    This sounds like the general description of a string-keyed map: you have three values, and you want to choose which one to use based on some string value.

    maps := map[string][]int{}
    
    set := input.Ask("Which set would you like to input to:")
    set = strings.toLower(set)
    for true {
        num := input.Ask("Number:")
        maps[set] = append(maps[set], num)
    }
    

    If it's important to you to only be able to use one of these three values, you can prepopulate the map

    maps := map[string][]int{
        "a": nil,
        "b": nil,
        "c": nil,
    }
    set := input.Ask("Which set would you like to input to (a, b, or c):")
    set = strings.toLower(set)
    if _, ok := maps[set]; !ok {
        fmt.Println("I don't know about that set")
        return
    }
    

    There's more information on maps in the language spec.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部