2_4.md - Error of implementation
k0pernicus opened this issue · 5 comments
k0pernicus commented
This is some code written in the blog :
trait Animal {
fn get_nom(&self) -> String {
self.nom
}
fn get_nombre_de_pattes(&self) -> usize {
self.nombre_de_pattes
}
}
struct Chien {
nom: String,
nombre_de_pattes: usize
}
struct Chat {
nom: String,
nombre_de_pattes: usize
}
struct Oiseau {
nom: String,
nombre_de_pattes: usize
}
struct Araignee {
nom: String,
nombre_de_pattes: usize
}
impl Animal for Chien {}
impl Animal for Chat {}
impl Animal for Oiseau {}
impl Animal for Araignee {}
fn affiche_animal<T: Animal>(animal: T) {
println!("Cet animal s'appelle {} et il a {} patte(s)", animal.get_nom(),
animal.get_nombre_de_pattes());
}
let chat = Chat { nom : "Félix", nombre_de_pattes: 4};
let spider = Araignee { nom : "Yuuuurk", nombre_de_pattes: 8};
affiche_animal(chat);
affiche_animal(spider);
Unfortunately, this code doesn't works because the compiler doesn't know, for the trait Animal with function get_nom, if the self 'object' has a field named 'nom'...
k0pernicus commented
In that case, we have to implement each function which use a field of &self in the impl <Trait> for <Struct>
's body
GuillaumeGomez commented
It certainly changed since I wrote the tuto (it was before the 1.0). If the code doesn't compile, it should be changed.
k0pernicus commented
I will update this code in few hours.
k0pernicus commented
I will update this code in few hours.
GuillaumeGomez commented
Perfect, I let you do it then. Thanks !