Skip to content

Instantly share code, notes, and snippets.

@j16r
Created June 27, 2014 01:02
Show Gist options
  • Save j16r/4969f4bfd961944db685 to your computer and use it in GitHub Desktop.
Save j16r/4969f4bfd961944db685 to your computer and use it in GitHub Desktop.
Generic Queue with Iterator
use std::default::Default;
struct Q<T> {
items : [T, ..10],
count : uint
}
impl<T : Default + Copy> Q<T> {
pub fn new() -> Box<Q<T>> {
box Q {items: [Default::default(), ..10],
count: 0}
}
pub fn empty(&self) -> bool {
self.count == 0
}
pub fn enqueue<T>(&mut self, item : T) {
self.items[self.count] = item;
self.count += 1
}
pub fn iter<'r, T>(&'r self) -> Box<QCursor<'r, T>> {
box QCursor {q: self, position: 0}
}
}
struct QCursor<'r, T> {
q : &'r Q<T>,
position : uint
}
impl<'r, T> Iterator<T> for QCursor<'r, T> {
fn next(&mut self) -> Option<T> {
if self.position >= self.q.count {
None
} else {
self.position += 1;
Some(self.q.items[self.position - 1])
}
}
}
#[test]
fn test_empty() {
let q = Q::<int>::new();
assert!(q.empty());
}
#[test]
fn test_enqueue() {
let mut q = Q::<int>::new();
q.enqueue(99);
assert!(!q.empty());
}
#[test]
fn test_iter() {
let mut q = Q::<int>::new();
q.enqueue(3);
q.enqueue(2);
q.enqueue(1);
let mut count = 0;
for item in q.iter() {
count += 1;
}
assert!(count == 3);
}
pub fn main() {
let mut q = Q::<int>::new();
q.enqueue(3);
q.enqueue(2);
q.enqueue(1);
for item in q.iter() {
print!("Item is {:i}\n", item);
}
}
@j16r
Copy link
Author

j16r commented Jun 27, 2014

rustc -o q_test --test q.rs
q.rs:68:3: 71:9 error: cannot determine a type for this expression: unconstrained type
q.rs:68 for item in q.iter() {
q.rs:69 count += 1;
q.rs:70 }
q.rs:71 assert!(count == 3);
q.rs:82:30: 82:34 error: cannot determine a type for this bounded type parameter: unconstrained type
q.rs:82 print!("Item is {:i}\n", item);
^~~~
note: in expansion of format_args!
:2:23: 2:75 note: expansion site
:1:1: 3:2 note: in expansion of print!
q.rs:82:5: 82:36 note: expansion site
make: *** [q_test] Error 101

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment