How can a function append a value to a vector and

2019-06-05 21:13发布

问题:

I'm trying to write a function rotate_card that accepts a vector as input, rotates the vector's front element to the rear, and returns a pair containing both the rotated element and the vector resulting from the rotation.

#[derive(Debug)]
enum Card {
    Ace,
    King,
    Queen,
    Jack,
}

type Deck = Vec<Card>;

fn rotate_card(deck: &mut Deck) -> (Card, &mut Deck) {
    let top_card = deck.remove(0);
    deck.push(top_card);
    (top_card, deck)
} // end rotate_card

fn main() {
    let mut my_deck: Deck = vec![Card::Ace, Card::King, Card::Queen, Card::Jack];
    let z: (Card, &mut Deck) = rotate_card(&mut my_deck);
    println!("The value of z is: {:?}.", z);
} // end main
error[E0382]: use of moved value: `top_card`
  --> src/main.rs:14:6
   |
13 |     deck.push(top_card);
   |               -------- value moved here
14 |     (top_card, deck)
   |      ^^^^^^^^ value used here after move
   |
   = note: move occurs because `top_card` has type `Card`, which does not implement the `Copy` trait

How do I work around the value used after move error?

回答1:

How do I work around

You don't "work around" this type of problem. Ownership is a fundamental concept in Rust and you have to understand it.

Solutions

Make your Card implicitly copyable via Copy

#[derive(Debug, Copy, Clone)]
enum Card { /* ... */ }

Make your Card explicitly copyable via Clone

#[derive(Debug, Clone)]
enum Card { /* ... */ }

fn rotate_card(deck: &mut Deck) -> Card {
    let top_card = deck.remove(0);
    deck.push(top_card.clone());
    top_card
}

Return a reference to the card

You can return a reference to the last card instead of the card as a value:

fn rotate_card(deck: &mut Deck) -> &mut Card {
    let top_card = deck.remove(0);
    deck.push(top_card);
    deck.last_mut().unwrap()
}

Use reference-counting

A type like Rc or Arc can allow shared ownership of a value:

use std::rc::Rc;

type Deck = Vec<Rc<Card>>;

fn rotate_card(deck: &mut Deck) -> Rc<Card> {
    let top_card = deck.remove(0);
    deck.push(top_card.clone());
    top_card
}

Other notes

This is a useless function signature:

fn rotate_card(deck: &mut Deck) -> (Card, &mut Deck) 

There's no reason to return the Deck back to the caller; they already have that reference. Remove that.

Slices (and Vecs via DerefMut) have the rotate_left method; you don't need to reimplement it.



标签: vector rust move