Description
Location
Summary
The examples are confusing because they use increasing integer sequences as both the vector elements and the range. This leas to a confusing example where you call vec.extend_from_within(2..);
and add 2..4
to the end of the vector. When I first read this, I assumed that it was adding the elements of the range to the end of the vector and that the vector had only been initialized with enough "extra room" for three more elements. It took me a while to realize that the range was specifying a range inside the vector and then appending it to the end. Looking back, the name extend_from_within
should have been a pretty good hint. However, every example adds numbers to the end that matches the first number of the provided range.
let mut vec = vec![0, 1, 2, 3, 4];
// Adds 2..4 to end of vector
vec.extend_from_within(2..);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
// Adds 0..1 to end of vector
vec.extend_from_within(..2);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
// Adds 4 (and then 2..4) to end of vector
vec.extend_from_within(4..8);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
If you think about the name of the method and the description of the method, you can figure out what this function does. However, the examples can be fairly misleading. I believe this can be rectified by using non-integer values in the vector. For example:
let mut vec = vec!['a', 'b', 'c'];
vec.extend_from_within(1..);
assert_eq!(vec, ['a', 'b', 'c', 'b', 'c']);
vec.extend_from_within(..1);
assert_eq!(vec, ['a', 'b', 'c', 'b', 'c', 'a', 'b']);
vec.extend_from_within(2..5);
assert_eq!(vec, ['a', 'b', 'c', 'b', 'c', 'a', 'b', 'c', 'b', 'c', 'a']);
Do others agree that this is an improvement? I know a lot of the other examples use integers, so maybe it's not worth making this example different. At the very least, we could improve it by using different numbers instead 0, 1, 2, etc.
let mut vec = vec![31, 37, 41, 43];
vec.extend_from_within(1..);
assert_eq!(vec, [31, 37, 41, 43, 37, 41, 43]);
vec.extend_from_within(..2);
assert_eq!(vec, [31, 37, 41, 43, 37, 41, 43, 31, 37]);
vec.extend_from_within(2..5);
assert_eq!(vec, [31, 37, 41, 43, 37, 41, 43, 31, 37, 41, 43, 37]);