]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/issue-15734.rs
Re-word explanation on closures in intro
[rust.git] / src / test / run-pass / issue-15734.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // If `Index` used an associated type for its output, this test would
12 // work more smoothly.
13
14 #![feature(old_orphan_check)]
15
16 use std::ops::Index;
17
18 struct Mat<T> { data: Vec<T>, cols: uint, }
19
20 impl<T> Mat<T> {
21     fn new(data: Vec<T>, cols: uint) -> Mat<T> {
22         Mat { data: data, cols: cols }
23     }
24     fn row<'a>(&'a self, row: uint) -> Row<&'a Mat<T>> {
25         Row { mat: self, row: row, }
26     }
27 }
28
29 impl<T> Index<(uint, uint)> for Mat<T> {
30     type Output = T;
31
32     fn index<'a>(&'a self, &(row, col): &(uint, uint)) -> &'a T {
33         &self.data[row * self.cols + col]
34     }
35 }
36
37 impl<'a, T> Index<(uint, uint)> for &'a Mat<T> {
38     type Output = T;
39
40     fn index<'b>(&'b self, index: &(uint, uint)) -> &'b T {
41         (*self).index(index)
42     }
43 }
44
45 struct Row<M> { mat: M, row: uint, }
46
47 impl<T, M: Index<(uint, uint), Output=T>> Index<uint> for Row<M> {
48     type Output = T;
49
50     fn index<'a>(&'a self, col: &uint) -> &'a T {
51         &self.mat[(self.row, *col)]
52     }
53 }
54
55 fn main() {
56     let m = Mat::new(vec!(1, 2, 3, 4, 5, 6), 3);
57     let r = m.row(1);
58
59     assert!(r.index(&2) == &6);
60     assert!(r[2] == 6);
61     assert!(r[2] == 6);
62     assert!(6 == r[2]);
63
64     let e = r[2];
65     assert!(e == 6);
66
67     let e: uint = r[2];
68     assert!(e == 6);
69 }