实现说明
函数 new、get、index、index_mut是实现的聚合点。
使用要点
- 直接运行文件,输出会带上标签,比如
cell:、safe lookup:——输出的每一行都能指回产生它的那次调用。 - 执行文件,
main会按顺序走完new、get。
常见问题
运行「为网格类型实现 Index」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 cell:、safe lookup: 这类标签。
签名一览:fn new(width: usize, height: usize, fill: T) -> Self
核心语句
fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut T {
&mut self.cells[y * self.width + x]
}
fn get(&self, x: usize, y: usize) -> Option<&T> {
if x >= self.width {
return None;
}
self.cells.get(y * self.width + x)
}
fn index(&self, (x, y): (usize, usize)) -> &T {
&self.cells[y * self.width + x]
}
代码示例
use std::ops::{Index, IndexMut};
struct Grid<T> {
width: usize,
cells: Vec<T>,
}
impl<T> Grid<T> {
fn new(width: usize, height: usize, fill: T) -> Self
where
T: Clone,
{
Grid { width, cells: vec![fill; width * height] }
}
// get 把越界决定权交还调用方:返回 Option 而不是 panic
fn get(&self, x: usize, y: usize) -> Option<&T> {
if x >= self.width {
return None;
}
self.cells.get(y * self.width + x)
}
}
// Index 让 grid[x, y] 下标语法成立:越界按 Vec 惯例 panic
impl<T> Index<(usize, usize)> for Grid<T> {
type Output = T;
fn index(&self, (x, y): (usize, usize)) -> &T {
&self.cells[y * self.width + x]
}
}
impl<T> IndexMut<(usize, usize)> for Grid<T> {
fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut T {
&mut self.cells[y * self.width + x]
}
}
fn main() {
let mut grid = Grid::new(3, 2, 0u8);
grid[(1, 0)] = 7;
println!("cell: {}", grid[(1, 0)]);
println!("safe lookup: {:?}", grid.get(5, 0));
}