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代码等效:


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

  func(c * GorpController)Create(dec * json.Decoder){
  <  / pre> 


  for someValue:= range dec {

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


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

2条回答 默认 最新

相关推荐 更多相似问题