Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 19, 2020 10:49
Show Gist options
  • Save rust-play/4dfe50a1cea5c5012d0b78481e76e1a1 to your computer and use it in GitHub Desktop.
Save rust-play/4dfe50a1cea5c5012d0b78481e76e1a1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
pub struct Monster {
hp: u8, // health points
sp: u8, // spell points
friends: Vec<Friend>,
}
pub struct Friend {
loyalty: u8,
}
impl Monster {
pub fn final_breath(&mut self) {
self.heal();
println!("Healing for {}", self.hp);
}
pub fn heal(&mut self) {
for f in self.friends.iter_mut(){
self.hp += f.loyalty;
self.sp -= f.loyalty;
}
}
}
// pub struct Monster {
// hp: u8, // health points
// sp: u8, // spell points
// friends: Vec<Friend>,
// }
// pub struct Friend {
// loyalty: u8,
// }
// impl Monster {
// pub fn final_breath(&mut self) {
// if let Some(friend) = self.friends.first() {
// self.heal(friend.loyalty);
// println!("Healing for {}", friend.loyalty);
// }
// }
// fn heal(&mut self, amount: u8) {
// self.hp += amount;
// self.sp -= amount;
// }
// }
// warning: cannot borrow `*self` as mutable because it is also borrowed as immutable
// --> src/main.rs:33:9
// |
// 31 | let friend = self.friends.first().unwrap();
// | ------------ immutable borrow occurs here
// 32 |
// 33 | self.heal(friend.loyalty);
// | ^^^^ -------------- immutable borrow later used here
// | |
// | mutable borrow occurs here
// |
// = note: `#[warn(mutable_borrow_reservation_conflict)]` on by default
// = warning: this borrowing pattern was not meant to be accepted, and may become a hard error in the future
// = note: for more information, see issue #59159 <https://github.com/rust-lang/rust/issues/59159>
// impl Monster {
// pub fn final_breath(&mut self) {
// // Error
// // if let Some(friend) = self.friends.first() {
// // self.heal(friend.loyalty);
// // println!("Healing for {}", friend.loyalty);
// // }
// self.change_heal();
// self.display_heal();
// }
// fn change_heal(&mut self){
// let friend = self.friends.first();
// self.heal(friend.loyalty);
// // if let Some(friend) = self.friends.first() {
// // self.heal(friend.loyalty);
// // }
// }
// fn display_heal(&self){
// if let Some(friend) = self.friends.first() {
// println!("Healing for {}", friend.loyalty);
// }
// }
// fn heal(&mut self, amount: u8) {
// self.hp += amount;
// self.sp -= amount;
// }
// }
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment