I want to learn how to use the Index
trait for my toy roguelike but can't even get it to work in a useless, dummy scenario.
use std::ops::Index;
// Dummy struct that wraps i32
#[derive(Clone, Copy, Debug)]
pub struct Integer {
pub val: i32,
}
impl Integer {
fn new(num: i32) -> Self {
Integer { val: num }
}
}
// Using the index operator on an Integer should add the index to the Integer's value.
// let i = Integer::new(20);
// i[20];
// The above code should make it so i.val == 40
impl Index<Integer> for Integer {
type Output = i32;
// The error is in the following line:
fn index(&self, to_add: Integer) -> &Self::Output {
self.val + to_add.val;
}
}
// The code causes an error before it reaches this
fn main() {
let mut i = Integer::new(20);
let mut n = Integer::new(30);
println!("i[20] is: {:?}", i[n]);
}
I get this error:
error[E0308]: mismatched types
--> src/main.rs:23:55
|
23 | fn index(&self, to_add: Integer) -> &Self::Output {
| _______________________________________________________^
24 | | self.val + to_add.val;
25 | | }
| |_____^ expected &i32, found ()
|
= note: expected type `&i32`
found type `()`
I don't really know what I'm talking about but I guess that the value dies before it reaches the end of the function or something like that? I don't yet fully understand lifetimes.
I know this looks like a "NO IDEA WHAT IM DOING FIX PLS" question, but I'd love to know what I'm doing wrong here so I can learn from it.