infomaniac
infomaniac

Reputation: 41

How can I simultaneously access data from and call a method from a struct?

For my first project I wanted to create a terminal implementation of Monopoly. I have created a Card, Player, and App structs. Originally my plan was to create an array inside the App struct holding a list of cards which I could then randomly select and run an execute() method on, which would push a log to the logs field of the App. What I thought would be best was this:

pub struct Card {
    pub group: u8,
    pub name: String,
    pub id: u8,
}

impl Card {
    pub fn new(group: u8, name: String, id: u8) -> Card {
        Card { group, name, id }
    }
    pub fn execute(self, app: &mut App) {
        match self.id {
            1 => {
                app.players[app.current_player].index = 24;
                app.push_log("this works".to_string(), "LOG: ".to_string());
            }
            _ => {}
        }
    }
}

pub struct Player<'a> {
    pub name: &'a str,
    pub money: u64,
    pub index: u8,
    pub piece: char,
    pub properties: Vec<u8>,
    pub goojf: u8, // get out of jail freeh
}

impl<'a> Player<'a> {
    pub fn new(name: &'a str, piece: char) -> Player<'a> {
        Player {
            name,
            money: 1500,
            index: 0,
            piece,
            properties: Vec::new(),
            goojf: 0,
        }
    }
}

pub struct App<'a> {
    pub cards: [Card; 1],
    pub logs: Vec<(String, String)>,
    pub players: Vec<Player<'a>>,
    pub current_player: usize,
}

impl<'a> App<'a> {
    pub fn new() -> App<'a> {
        App {
            cards: [Card::new(
                11,
                "Take a ride on the Penn. Railroad!".to_string(),
                0,
            )],
            logs: vec![(
                String::from("You've begun a game!"),
                String::from("BEGIN!:"),
            )],
            players: vec![Player::new("Joe", '@')],
            current_player: 0,
        }
    }
    pub fn draw_card(&mut self) {
        if self.players[self.current_player].index == 2
            || self.players[self.current_player].index == 17
            || self.players[self.current_player].index == 33
        {
            self.cards[0].execute(self);
        }
    }
    pub fn push_log(&mut self, message: String, status: String) {
        self.logs.push((message, status));
    }
}
fn main() {}

However this code throws the following error:

error[E0507]: cannot move out of `self.cards[_]` which is behind a mutable reference
  --> src/main.rs:76:13
   |
76 |             self.cards[0].execute(self);
   |             ^^^^^^^^^^^^^ move occurs because `self.cards[_]` has type `Card`, which does not implement the `Copy` trait

I managed to fix this error by simply declaring the array of cards in the method itself, however, this seem to be pretty brute and not at all efficient, especially since other methods in my program depend on cards. How could I just refer to a single array of cards for all of my methods implemented in App or elsewhere?

Upvotes: 0

Views: 518

Answers (2)

Locke
Locke

Reputation: 8980

Does a card need to be able to mutate the cards in self? If you know that execute will not need access to cards, the easiest solution is to split App into further structs so you can better limit the access of the function.

Unless there is another layer to your program that interacts with App as a singular object, requiring everything be in a single struct to perform operations will likely only constrain your code. If possible it is better to split it into its core components so you can be more selective when sharing references and avoid needing to make so many fields pub.

Here is a rough example:

pub struct GameState<'a> {
    pub players: Vec<Player<'a>>,
    pub current_player: usize,
}


/// You may want to look into using https://crates.io/crates/log instead to make logging easier.
pub struct Logs {
    entries: Vec<(String, String)>,
}

impl Logs {
    /// Use ToOwned so you can use both both &str and String
    pub fn push<S: ToOwned<String>>(&mut self, message: S, status: S) {
        self.entries.push((message.to_owned(), status.to_owned()));
    }
}

pub struct Card {
    group: u8,
    name: String,
    id: u8,
}

impl Card {
    pub fn new(group: u8, name: String, id: u8) -> Self {
        Card { group, name, id }
    }

    /// Use &self because there is no reason we need are required to consume the card
    pub fn execute(&self, state: &mut GameState, logs: &mut Logs) {
        if self.id == 1{
            state.players[state.current_player].index = 24;
            logs.push("this works", "LOG");
        }
    }
}

Also as a side note, execute consumes a card when called since it does not take a reference. Since Card does not implement Copy, that would require it be removed from cards so it can be moved.

Misc Tips and Code Review

Using IDs

It looks like you frequently use IDs to distinguish between items. However, I think your code will look cleaner and be easier to write if you used more human readable types. For example, do cards need an ID? Usually it is preferable to define your struct based on how the data is used. Last time I played monopoly, I don't remember picking up a card and referring to the card ID to determine what to do. I would instead recommend defining a Card by how it is used in the came. If I am remembering correctly, each card contains a short message telling the player what to do. Technically a card could consist of just the message, but you can instead make your code a bit cleaner by separating out the action to an enum so actions are not hard coded to the text on the card.

pub struct Card {
    text: String,
    action: CardAction,
}

// Note: enums which can also hold data, are more commonly referred to as 
// "tagged unions" in computer science. It can be a pain to search for them if 
// you don't know what they are called.
pub enum CardAction {
    ProceedToGo,
    GoToJail,
    GainOrLoseMoney(i64),
    // etc.
}

On a similar note, it looks like you are trying to be memory conscious by using the smallest type required for a given value. I would recommend against this thinking. If a value of 253u8 is equally as invalid as 324234i32, then the smaller type is not doing anything to help you. You might as well use i32/u32 or i64/u64 since most systems will have an easier time operating on these types. The same thing goes for indices and using other integer types instead of usize since choosing to use another type will only give you more work converting it to and from a usize.

Sharing Owned References

Depending on your design philosophy you might want to store a reference to a struct in multiple places. This can be done using a reference counter Rc<T>. Here are some quick examples. Note that these can not be shared between threads.

let property: Rc<Property> = Rc::new(Property::new(/* etc */));

// Holds an owned reference to the same property as property that can be accessed immutably
let ref_to_property: Rc<Property> = property.clone();

// Or if you want interior mutability you can use Rc<RefCell<T>> instead.
let mutable_property = Rc::new(RefCell::new(Property::new(/* etc */)));

Upvotes: 1

cdhowie
cdhowie

Reputation: 169403

As others have pointed out, Card::execute() needs to take &self instead of self, but then you run into the borrow checker issue, which I'll spend the rest of this answer discussing.

It may seem odd, but Rust is actually protecting you here. The borrow checker does not look into functions to see what they do, so it has no idea that Card::execute() won't do something to invalidate the referenced passed as the first argument. For example, if App::cards was a vector instead of an array, it could clear the vector.

Something that could actually practically happen here to cause undefined behavior would be if Card::execute() took a string slice from self.name and then cleared the card's name attribute through the mutable reference to app. None of these actions would be prohibited, and you'd be left with an invalid reference to a string slice. This is why the borrow checker isn't letting you make this method call, and this is exactly the kind of accident that Rust is designed to prevent.

There's a few ways around this. One option is to only pass the pieces of the App value needed to complete the task. You can borrow different parts of the same value. The problem here is that the reborrow of self overlaps with the borrow self.cards[0]. Passing each field separately isn't very ergonomic though, as in this case you'll wind up having to pass a reference to pretty much everything else on App.

It looks like the Card values don't actually contain any game state, and are used as data for the game engine. If this is the case, then the cards can live outside of App, like so:

pub struct App<'a> {
    // Changed to an unowned slice.
    pub cards: &'a [Card],
    pub logs: Vec<(String, String)>,
    pub players: Vec<Player<'a>>,
    pub current_player: usize,
}

impl<'a> App<'a> {
    pub fn new(cards: &'a [Card]) -> App<'a> {
        App {
            cards,
            // ...

Then in your main() you can initialize the data and borrow it:

fn main() {
    let cards: [Card; 1] = [Card::new(
        11,
        "Take a ride on the Penn. Railroad!".to_string(),
        0,
    )];
    
    let app = App::new(&cards);
}

This solves the compilation problem. I'd suggest making other changes, as well:

  • App should probably be renamed GameState or something to emphasize that this struct should contain only mutable game state, and no immutable reference data.
  • Player's name field should probably be an owned String instead of an unowned &str, otherwise some other entity in the program will need to own a string slice for the duration of the program so that Player can borrow it.

Upvotes: 2

Related Questions