本文介绍了无法移出 Rust 中借用的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pub struct Character {
    name: String,
    hp: i32,
    level: i32,
    xp: i32,
    xp_needed: i32,
    gold: i32
}

impl Character {
    pub fn new(name: String) -> Character {
        let mut rng = thread_rng();

        let hp: i32 = rng.gen_range(12, 75);
        let gold: i32 = rng.gen_range(10, 50);

        Character { name: name, hp: hp, level: 1, xp: 0, gold: gold, xp_needed: 100 }
    }

    pub fn get_name(&self) -> String {
        self.name
    }

    // ...
}

我到底在什么地方违反了规则?

How exactly am I breaking the rules here?

在高层次上,这对 Rust 来说是不合时宜的.你不能转让借来的东西的所有权,因为你不拥有它.

嗯,不是吗?我还有其他功能,例如:

Um don't I? I have other functions like:

pub fn get_hp(&self) -> i32 {
    self.hp
}

而且效果很好.

   |
23 |         self.name
   |         ^^^^ cannot move out of borrowed content

error: aborting due to previous error

这是怎么回事?返回字符名称的适当方法是什么?为什么 get_hp 方法有效而 get_name 无效?

What's going on? What is the appropriate approach to return the character name? Why does the get_hp method work but not get_name?

推荐答案

get_hpget_name 的区别在于 get_hp 返回一个 i32.i32 是一个 Copy类型.Copy 类型可以通过简单地复制位来复制并且永远不会移出.另一方面,String 不是 Copy,它管理一些必须转移(移出)或 Cloned.

The difference between get_hp and get_name is that get_hp returns a i32. i32 is a Copy type. Copy types can be copied by simply copying bits and are never moved out. On the other hand String is not Copy, it manages some memory which must either be transferred (moved out) or Cloned.

对于这样的 getter,返回引用而不是克隆更为惯用.对于 Strings,它应该特别 &str.

For getters like this, it is more idiomatic to return references instead of cloning. And for Strings, it should specifically be &str.

pub fn get_name(&self) -> &str {
    &self.name
}

这篇关于无法移出 Rust 中借用的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:23