问题描述
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_hp
和 get_name
的区别在于 get_hp
返回一个 i32.i32
是一个 Copy
类型.Copy
类型可以通过简单地复制位来复制并且永远不会移出.另一方面,String
不是 Copy
,它管理一些必须转移(移出)或 Clone
d.
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 Clone
d.
对于这样的 getter,返回引用而不是克隆更为惯用.对于 String
s,它应该特别 是 &str
.
For getters like this, it is more idiomatic to return references instead of cloning. And for String
s, it should specifically be &str
.
pub fn get_name(&self) -> &str {
&self.name
}
这篇关于无法移出 Rust 中借用的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!