Hi all,
I want to implement an iterator that returns a reference into the
iterator struct from the next() call.
Usually I'd write something like:
fn next<'a>(&'a mut self) -> Option<&'a ...>
but this breaks the Iterator<T> trait. I now have the following code
that works, but I am unsure if it is correct or not.
use std::mem::transmute; // std::cast::transmute
struct Iter {
current: uint
}
impl<'a> Iterator<&'a uint> for Iter {
fn next(&mut self) -> Option<&'a uint> {
Some(unsafe { transmute(&self.current) } )
}
}
fn main() {
let mut iter = Iter { current: 2 };
for &i in iter {
println!("{}", i);
}
}
Actually what I want is to declare that 'a (&self.current) is of shorter
or equal lifetime than &self, but I don't know how.
I found out that my code is of course wrong, as the following code
produces a memory protection fault.
use std::mem::transmute;
struct Iter { current: ~str }
impl<'a> Iterator<&'a ~str> for Iter {
fn next(&mut self) -> Option<&'a ~str> {
Some(unsafe { transmute(&self.current) } )
}
}
fn foo<'a>() -> &'a ~str {
let mut iter = Iter { current: "hello".to_owned() };
return iter.next().unwrap();
}
fn main() {
println!("{}", foo());
}
Any hints?
Regards,
Michael
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev