dongtanxi5676756 2018-12-13 13:42
浏览 50
已采纳

以编程方式创建嵌套数组

I want to test my serialization format for robustnes and want to serialize a nested array. The Serialization actually dies at some point, but I don't know at what depth exactly. Right now I just define a large array manually, but I want to do it programatically, so I can figure out when exactly the depth is too high. Changing the code for each iteration is tedious...

l := [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]string {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{"a"}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}

What I want is something like this:

l := "a"
while(1){
    l = {l} //nest the slice/array once more
    print("round ", i)
    i++
}

I'm a Golang newbie and I don't know how I can get around the type-safety in this case.

  • 写回答

1条回答 默认 最新

  • dongwei2610 2018-12-13 14:24
    关注

    In go you can't change the type of a variable so you need to use interface{} as type var l interface{} now you could do something like:

    l = "a"
    for i:= 0;i<3;i++{
        l = []interface{}{l}
    }
    

    printing l would give the output [[[a]]], same as [][][]string{{{"a"}}}.

    A problem is that you lose your type and it will be impossible to do something like l[0][0][0] to get the value. As far as I now you would need to cast everything l.([]interface{})[0].([]interface{})[0].([]interface{})[0].(string)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案