douhang1913 2014-10-04 18:58
浏览 89
已采纳

Go或Rust中的数组数组?

I'm porting some old PHP script to Go in order to achieve better performance. However, the old PHP is full of multidimensional arrays. Some excerpt from the codebase:

while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
    $someData[$row['column_a']][$row['column_b']] = $row;
}

// ... more queries and stuff

if (isset($moreData['id']) && isset($anotherData['id']) && $someData[$anotherData['id']][$moreData['id']]) {
    echo $someData[$anotherData['id']][$moreData['id']];
}

Awful, i know, but i can't change the logic. I made the whole script perform much better by compiling with phc, but moving to a procedural, statically-typed language seems like a better move. How can i replicate those data structures efficiently with Go or Rust? It needs to be fault-tolerant when it comes to checking indexes, there's a lot of issets all around the script to check if the identifiers exist in the data structures.

  • 写回答

2条回答 默认 最新

  • dpu66046 2014-10-05 01:35
    关注

    In Go, this would be represented as a map. The syntax is map[key]value. So for example to store a multidimensional map of [string, string] -> int it would be map[string]map[string]int. If you know your indices are integers and densely packed, then you'd want to use slices. Those are simpler and look like [][]type.

    As for the checking for a key existing, use this syntax, where m is a map:

    if val, ok := m[key1][key2]; ok {
        ///Do something with val
    }
    

    Remember that to add a key to a multidimensional map you'd have to make sure the inner map is allocated before adding to it.

    if _, ok := m[key]; !ok {
        m[key] = make(map[string]int)
    }
    m[key1][key2] = value
    

    Obviously you'd want to wrap this up in a type with methods or a few simple functions.

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

报告相同问题?

悬赏问题

  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论