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.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名