It doesn’t seem like it conveys what I want to say to the compiler.
What I want to say is “set this range of values equal to the right hand side”. What the for loop says is “set each value equal to the right hand side”.
Suppose the example were more complicated. A natural reading of this code would be “Create a random number and set the a…b range of x equal to it”:
x[a..b] = rand::thread_rng().gen();
A natural reading of this code would be “Create b-a random numbers in series and set the a…b indices of x equal to the corresponding random number”:
for i in a..b {
x[i] = rand::thread_rng().gen();
}
You can of course express the alternative:
let rn = rand::thread_rng().gen();
for i in a..b {
x[i] = rn;
}
but that’s still subtly different - “Set each a…b value of x to rn”.
Eg consider the situation where x refers to a compressed series where setting a range of the same value is an O(1) operation, but setting individual entries is an O(n) operation. I’m somewhat dubious that that sort of situation is prevalent enough to expose an extra trait for setting a range to a type equal to the individual entries, but at least an implicit memset for basic types would be some nice syntactic sugar.
The “fill” solution suggested above seems less clean semantically but if not overloading the assignment operator is a core tenet of the language then I think it’s still a step up from where it is now, since there are already helper functions for slices.
If the compiler is smart enough to take a look at a for loop and optimize away the whole thing and replace it with a call to the compiler-intrinsic memset, that’s more intelligence than I’d assume.
EDIT: One more point I’d add is that with the “set range to scalar” or “fill” solution, the compiler / fill function would be free to do the operation in parallel (if possible) without violating the apparent semantics of the language. Conversely, with a for loop, the implicit copy() called on the scalar could hypothetically have side effects which were intended to be executed in series. Inspecting the copy function to determine if a parallel optimization of the for loop is safe might not be possible if it’s pulled in from a shared binary.