dqpkea9486 2018-02-03 19:11
浏览 81
已采纳

C ++风格的Golang迭代器

I've started to learn the Go, and I know the C++ language. Can work with slices or lists in go in the same way in C++? For example, in C++ we can use iterators for point to the position in a collection, like it shown above:

#include <list>

int main() {
    std::list<int> list = {1,1,2,3,1,4,5,6,7,8,1,1,9,10};
    auto it = std::find(list.begin(), list.end(), 3);
    // Now I can use the 'it' for insert items, remove/transform diaposonces etc.
   ++it;
   list.erase(it, std::remove(it, list.end(), 1);
}

And iterate forward/back as we wish. What is a good practice for tasks like this? What is the most efficient way to work with iterators in Golang?

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-02-03 19:45
    关注

    Go and C++ are very different languages. Don't try to use C++ STL style in Go. Other Go programmers won't see what you are trying to do.

    Almost all Go code I've worked with uses array/slice indexes not iterators. In the odd case that a linked list makes sense you only hold head, tail pointers.

    Trying to write STL style code needs templates that Go does not have. Trying to write “generic” code in Go results in horrific disasters of interface{} and reflection that read ugly and perform 5x worse than they should.

    Just write Go style code in Go.

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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题