douyou7102
2015-11-10 19:35
浏览 44
已采纳

如何遍历解码器?

I come from a Python background and so have a tendency to think in terms of iterators. It seems to me that the range keyword in Go intends for us to think in a nearly identical way, so I would like to do somthing semantically equivalent to this Python code in Go:

for obj in json_decoder:
    # business logic

Here is the motivating case in Go; consider the following function:

func (c *GorpController) Create(dec *json.Decoder) {
    // business logic
}

I would like to be able to implement it as:

for someValue := range dec {
    // business logic
}

Is there some sort of way to use range with a Decoder interface? A function that wraps it in a different interface would be ideal, and an idiomatic pattern would be acceptable.

Thank you!

图片转代码服务由CSDN问答提供 功能建议

我来自Python背景,因此倾向于考虑迭代器。 在我看来,Go中的 range 关键字旨在让我们以几乎相同的方式进行思考,因此我想在语义上做一些事与Go中的Python代码等效:

 用于json_decoder中的obj:
#业务逻辑
   
 
 

这是Go中的激励案例; 考虑以下函数:

  func(c * GorpController)Create(dec * json.Decoder){
 //业务逻辑
} 
  <  / pre> 
 
 

我希望能够将其实现为:

  for someValue:= range dec {
 //业务逻辑
  } 
   
 
 

是否可以通过 Decoder 接口使用 range ? 将其包装在不同接口中的函数将是理想的,并且可以接受惯用模式。

谢谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题