Why learning rust trait, I noticed something significant with the compiler.
First of all, I also want to say that the compiler is very helpful in resolving errors.
I noticed that adding semicolon to my code gave me an error i wasn't expecting:
| fn name(&self) -> &'static str{
| ______________________________^
46 | | self.name;
| | - help: consider removing this semicolon
47 | | }
| |^ expected reference, found ()
|
= note: expected type&'static str
found type()
But after removing it, the code works great. please can someone explain why the semicolon was throwing that error, because am coming in from a C programming background (PHP,JS) and semicolon is the way to go.
here is my code that works:
struct Dog{
name: &'static str,
mood: &'static str,
breed: &'static str
}
trait Animal {
fn new(name: &'static str) -> Self;
fn name(&self) -> &'static str;
fn mood(&self) -> &'static str;
fn breed(&self) -> &'static str;
fn noise(&self) -> &'static str;
fn sound(&self){
println!("{} a {} dog {} when {}", self.name(), self.breed(),self.noise(),self.mood());
}
}
impl Animal for Dog{
fn new(name: &'static str) -> Dog {
Dog {
name: name,
mood: "happy",
breed: "local"
}
}
fn name(&self) -> &'static str{
self.name
}
fn mood(&self) -> &'static str{
self.mood
}
fn breed(&self) -> &'static str{
self.breed
}
fn noise(&self) -> &'static str{
if self.mood == "happy"{
"bark"
}
else{
"whine"
}
}
}
fn main() {
println!("Hello");
let bingo: Dog = Animal::new("Bingo");
bingo.sound();
}