Skip to content

Instantly share code, notes, and snippets.

@shadowmint
Last active August 29, 2015 14:08
Show Gist options
  • Save shadowmint/f9106c755b029ad0bbde to your computer and use it in GitHub Desktop.
Save shadowmint/f9106c755b029ad0bbde to your computer and use it in GitHub Desktop.
Lifetime error with traits?
pub enum DataType {
IsView,
IsStatic,
IsNone
}
/// Hold various possible types of data
pub struct Data {
data: Trait<Box<Array<u8> + 'static>, DataType>
}
impl Data {
/// Create a new view from an existing string
pub fn view<'a>(src:&'a Array<u8>, offset:uint, length:uint) -> Data {
let data:Box<Array<u8>> = box View::new(src, offset, length);
return Data {
data: Trait::new(data, IsView)
}
}
...
}
src/data.rs:39:45: 39:48 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
src/data.rs:39 let data:Box<Array<u8>> = box View::new(src, offset, length);
^~~
src/data.rs:41:15: 41:39 note: first, the lifetime cannot outlive the call at 41:14...
src/data.rs:41 data: Trait::new(data, IsView)
^~~~~~~~~~~~~~~~~~~~~~~~
src/data.rs:41:26: 41:30 note: ...so that argument is valid for the call
src/data.rs:41 data: Trait::new(data, IsView)
^~~~
src/data.rs:39:45: 39:48 note: but, the lifetime must be valid for the expression at 39:44...
src/data.rs:39 let data:Box<Array<u8>> = box View::new(src, offset, length);
^~~
src/data.rs:39:45: 39:48 note: ...so that auto-reference is valid at the time of borrow
src/data.rs:39 let data:Box<Array<u8>> = box View::new(src, offset, length);
^~~
error: aborting due to previous error
Could not compile `txt`.
/// This is a container for trait implementations
pub struct Trait<Sized? T> {
data:Option<*mut T>
}
impl<Sized? T> Trait<T> {
/// Create a new trait box for a type
pub fn new(data:Box<T>) -> Trait<T> {
unsafe {
let value:*mut T = transmute(data);
return Trait {
data: Some(value)
};
}
}
...
}
pub struct View<'a, T> {
len: uint,
data: *const T,
parent:&'a Array<T> + 'a,
}
impl<'a> View<'a, ()> {
/// New array view
pub fn new<'a, T: Default + Clone + PartialEq>(parent:&'a Array<T>, offset:uint, mut length:uint) -> View<'a, T> {
if (offset + length - 1) >= parent.len() {
length = parent.len() - offset;
}
return View {
parent: parent,
len: length,
data: parent.offset(offset)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment