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条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条