On Wednesday, October 17, 2012 10:08:15 H. S. Teoh wrote: > On Wed, Oct 17, 2012 at 06:58:52PM +0200, Jacob Carlborg wrote: > > On 2012-10-17 17:45, Jonathan M Davis wrote: > > >Well, what would you expect? Ranges are consumed when you iterate > > >over them. So, if an container is a range, it will be consumed when > > >you iterate over it. That's the way that it _has_ to work given how > > >ranges work, and that's why you overload opSlice to return a range > > >which is iterated over rather than making the container itself a > > >range. > > > > How does this work with built-in arrays? > > [...] > > If I understand it correctly, arrays work because when you pass an array > to a range function, you're actually passing a slice of it to the > function. That slice gets consumed, but the original array is unchanged.
Pretty much yeah. Thinking of arrays in D as containers in a mistake really. They're not, as weird as that may be. It's the runtime (or the block of memory in the runtime, depending on how you look at it) which is the container, and the array is just a slice into it. But even that's not really an accurate way of looking at it, because you can append to them (altering the size of the underlying container and possibly resulting in them pointing to a different block of memory). Kind of like how arrays are halfway between value types and reference types, they're sort of halfway between ranges and containers. It's quite unfortunate that arrays are by far the most commonly used type of range, because they're a horrible example of one when you get down to the details of how they work. Regardless, it's slicing that you're dealing with when doing range-based operations on arrays, so it's the slice that gets operated on and consumed rather than the original array. And just like how ranges which are structs normally get automatically saved when passed to functions, arrays automatically get saved because they get sliced. And foreach doesn't even use the range API on arrays anyway, so regardless of how they work as ranges, it wouldn't necessarily apply to foreach. - Jonathan M Davis