函数如何将值附加到向量并返回该值? [英] How can a function append a value to a vector and also return that value?

查看:43
本文介绍了函数如何将值附加到向量并返回该值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数 rotate_card,它接受一个向量作为输入,将向量的前面元素旋转到后面,并返回一个包含旋转元素和由旋转.

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

如何解决移动后使用的值错误?

推荐答案

我如何解决

您不会解决"此类问题.所有权是 Rust 中的一个基本概念,您必须了解它.

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

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

使您的 Card 通过 Clone

明确可复制

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()
}

使用引用计数

RcArc 都可以允许共享值的所有权:

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) 

没有理由将 Deck 返还给调用者;他们已经有那个参考.删除那个.

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

切片(和 Vec 通过 DerefMut)具有 rotate_left 方法;你不需要重新实现它.

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

这篇关于函数如何将值附加到向量并返回该值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆