Je veux apprendre à utiliser le trait Index
pour mon jouet roguelike mais je ne peux même pas le faire fonctionner dans un scénario fictif inutile.Comment implémenter std :: ops :: Index pour faire muter la valeur en cours d'indexation?
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]);
}
Je reçois cette erreur:
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 `()`
Je ne sais pas vraiment ce que je parle, mais je suppose que la valeur meurt avant d'atteindre la fin de la fonction ou quelque chose comme ça ? Je ne comprends pas encore complètement les vies. Je sais que cela ressemble à une question "AUCUNE IDÉE QU'IL FAUT FAIRE FIXER", mais j'aimerais savoir ce que je fais de mal ici afin que je puisse apprendre de lui.
Signature 'index' est' index (& self, Idx) -> & Self :: Output', pas 'index (mut self, ...) ...' ' – red75prime