dpmwy80068 2019-07-22 03:04
浏览 50

如何打开切片

How can i unpack a slice in golang?

I have a slice,

var a = [1,2,3,4,5, ...n ]

What i want to achieve is to be able to generate new variables dynamically for the length of the slice. The output should look something like this

Var a = 1, b= 2, c=3, n=last number in slice
  • 写回答

1条回答 默认 最新

  • dongluyi5123 2019-07-22 04:24
    关注

    I am considering that the thing you want is dynamic variable allocation. I guess you cannot do so. Instead you can use Go Map to store your data as key-value format.

    func main() {
        mySlice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        myVariables := make(map[string]int)
        ch := 'a'
        for _, value := range mySlice {
            key := fmt.Sprintf("%c", ch)
            myVariables[key] = value
            ch++
        }
        fmt.Println(myVariables)
    }
    
    

    The output will be:

    map[a:1 b:2 c:3 d:4 e:5 f:6 g:7 h:8 i:9 j:10]
    

    You can also generate the key name randomly, visit here for details

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度