Closed
Description
Updated report
It appears that iterators over vectors of 0-sized values are not currently valid:
fn main() {
assert!(vec!(()).iter().len() == 1);
}
Original report
rust 0.10 for loop ignores trait methods on unit-like structs
Using Rust 0.10 on Windows. If I call a for loop on structs that implement a trait method, structs with attributes have their methods called. Unit-like structs do not. As far as I can tell, the for loop never iterates despite there being an object to iterate upon.
Calling the methods in other contexts (directly, or in a vec cast to trait) works as expected.
trait GetAttribute {
fn get_attribute(&self) -> int;
}
struct VariableAttribute {
attribute: int
}
impl GetAttribute for VariableAttribute {
fn get_attribute(&self) -> int {
self.attribute
}
}
struct UnitLike;
impl GetAttribute for UnitLike {
fn get_attribute(&self) -> int {
4
}
}
fn main() {
let va = VariableAttribute{attribute: 1};
let ul = UnitLike;
// Calling the method on each object individually works.
let mut total = 0;
total += va.get_attribute();
total += ul.get_attribute();
assert_eq!(total, 5);
// Placing each object in a vector cast to the trait,
// then calling the method on each object works.
let cast_vec = vec!(&va as &GetAttribute, &ul as &GetAttribute);
let mut cast_vec_total = 0;
for object in cast_vec.iter() { cast_vec_total += object.get_attribute() }
assert_eq!(cast_vec_total, 5);
// However, placing each object in their own, non-cast vectors,
// then calling the method on each object fails
let va_vec = vec!(va);
let sa_vec = vec!(ul);
let mut noncast_vec_total = 0;
for object in va_vec.iter() { noncast_vec_total += object.get_attribute() }
for object in sa_vec.iter() { noncast_vec_total += object.get_attribute() }
// The sa vector does have a length...
assert_eq!(1, sa_vec.len());
// ... But without a variable in the struct, the for loop doesn't even care.
for object in sa_vec.iter() { println!("I never even get called. :("); }
// And thus we get 1.
assert_eq!(noncast_vec_total, 5);
}
Metadata
Metadata
Assignees
Labels
No labels