Closed
Description
STR
// Sorry for the long example, didn't have time to make it shorter!
struct Mat<T> {
data: Vec<T>,
shape: (uint, uint),
}
impl<T> Mat<T> {
fn new(data: Vec<T>, shape@(nrows, ncols): (uint, uint)) -> Mat<T> {
assert!(data.len() == nrows * ncols);
Mat {
data: data,
shape: shape,
}
}
fn row<'a>(&'a self, row: uint) -> Row<&'a Mat<T>> {
let (nrows, _) = self.shape;
assert!(row < nrows);
Row {
mat: self,
row: row,
}
}
}
impl<T> Index<(uint, uint), T> for Mat<T> {
fn index<'a>(&'a self, &(row, col): &(uint, uint)) -> &'a T {
let (nrows, ncols) = self.shape;
assert!(row < nrows, col < ncols);
&self.data[row * ncols + col]
}
}
impl<'a, T> Index<(uint, uint), T> for &'a Mat<T> {
fn index<'b>(&'b self, index: &(uint, uint)) -> &'b T {
(*self).index(index)
}
}
struct Row<M> {
mat: M,
row: uint,
}
impl<T, M: Index<(uint, uint), T>> Index<uint, T> for Row<M> {
fn index<'a>(&'a self, col: &uint) -> &'a T {
&self.mat[(self.row, *col)]
}
}
fn main() {
let m = Mat::new(vec!(1u, 2, 3, 4, 5, 6), (2, 3));
let r = m.row(1);
// GOOD
println!("{}", r.index(&2) == &6);
// BAD the sugary version doesn't work
println!("{}", r[2] == 6);
// BAD type annotating the index/rhs doesn't help...
println!("{}", r[2u] == 6u);
// GOOD it works OK in reverse...
println!("{}", 6 == r[2]);
// BAD indirection has no positive effect
let e = r[2];
println!("{}", e == 6);
// GOOD unless it's type annotated
let e: uint = r[2];
println!("{}", e == 6);
}
All the lines marked with BAD
yield these errors:
r[2] == 6: cannot determine a type for this bounded type parameter: unconstrained type
r[2u] == 6u: the type of this value must be known in this context
e == 6: the type of this value must be known in this context
Version
$ rustc --version
rustc 0.12.0-pre (459ffc2adc74f5e8b64a76f5670edb419b9f65da 2014-07-17 01:16:19 +0000)