Go: proposal: Support custom collection types in template range

Created on 3 Mar 2019  路  5Comments  路  Source: golang/go

The only loop construct available in Go templates is the range keyword, which currently is restricted to an array, slice, map, or a channel.

It would be _really_ useful if range also could support custom list and map types, as that would enable:

  • Collections with different characteristics than the built-ins: ordered maps, immutable collections (one example would be the very promising immutable from @benbjohnson) etc.
  • Wrapping slices and maps in a struct so they can be stateful (have fields)

The immutable library above has outlined some nice interfaces that could be inspirational, the core part of MapIterator included as an example:

type MapIterator interface {
   Done() bool
   Next() (key, value interface{})
}

I'm confident that you will get many hands raised if you ask around "_do Go templates need a more powerful loop construct?_" The alternative to this proposal would possibly be to add a for keyword, but I think it would be better to leave the complexities to the Go code.

FrozenDueToAge Proposal

Most helpful comment

FYI I鈥檝e been thinking about generalized range loops at the Go language level. I plan to open an issue for discussion at some point soon; the delay has been that I don鈥檛 yet have a proposal to put on the table that I really like. But it seems I should start a place to have that discussion, anyway.

All 5 comments

@bep is this a proposal, or a feature request?

@bep is this a proposal, or a feature request?

It's a proposal for a feature request. I have not studied the definitions to know where the lines go. I don't see how this feature could break anything, but it probably needs some more thought before it's implemented (mainly to get the interface right; it probably also need a method to get one item by index (so it can be used by the index func) and a way to get the length of the list/map so it can be used in the len func).

Go templates are modeled on Go itself as far as what is provided. We should figure out what the story is for generalized iteration in Go's own for range before we put something in template. If we do template first there's a good chance we just end up with something different in Go, add that too, and now we have two in template.

See #24282, #15292 and maybe some other issues.

Can close this. If we do make a change for Go itself we will remember to come back to template.

FYI I鈥檝e been thinking about generalized range loops at the Go language level. I plan to open an issue for discussion at some point soon; the delay has been that I don鈥檛 yet have a proposal to put on the table that I really like. But it seems I should start a place to have that discussion, anyway.

Was this page helpful?
0 / 5 - 0 ratings