![](/img/trans.png)
[英]Rust: return a generic struct from a function where (only) <T> is different
[英]When do you take input as T or &T in a Rust generic function?
我的課堂筆記中有實現HasArea
特征並打印區域的代碼,類似於Rust Book示例。 教授的筆記如下:
trait HasArea<T> {
fn area(& self) -> T,
}
fn print<T: Display, S: HasArea<T>>(s: &S) {
println!("", s.area()); // println sth must impl Display trait
}
struct Circle {
x: T,
y: T,
r: T,
}
impl <T: Copy + Mul <Output = T>>
HasArea<T> for Circle<T>
{
fn area(&self) -> T {
self.r * self.r
}
}
將其與使用shape: T
作為輸入的Rust Book進行比較:
trait HasArea {
fn area(&self) -> f64;
}
struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl HasArea for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
fn print_area<T: HasArea>(shape: T) {
println!("This shape has an area of {}", shape.area());
}
fn main() {
let c = Circle {
x: 0.0f64,
y: 0.0f64,
radius: 1.0f64,
};
print_area(c);
}
我不確定為什么教授使用s: &S
,而Rust Book使用shape: T
。 在實現泛型函數時,何時將輸入傳遞為x: &T
和何時x: T
時,誰能幫助比較?
在實現泛型函數時,何時將輸入傳遞為
x: &T
和何時x: T
時,誰能幫助比較?
就像您接受x: Foo
和x: &Foo
。 接受x: Foo
賦予函數x
的所有權,並且(除非x
是Copy
)調用方將無法再次使用它。
在Rust Book示例中, print_area
擁有circle
的所有權,因此您不能在print_area(circle);
之后使用circle
print_area(circle);
線。 例如,以下內容:
fn main() {
// ...
print_area(c);
print_area(c);
}
拋出此錯誤:
error[E0382]: use of moved value: `c`
--> <anon>:29:16
|
28 | print_area(c);
| - value moved here
29 | print_area(c);
| ^ value used here after move
|
= note: move occurs because `c` has type `Circle`, which does not implement the `Copy` trait
以我的經驗,大多數時候您會想: &T
(就像您的教授的筆記)。 僅當需要結構的所有權時,才需要使用: T
。 Rust Book可能使用: T
為簡單起見。
這不是仿制葯的問題,而是借用和所有權的問題。 如果您想將輸入移到函數中,請使用T
;否則,如果您只是想借用它,請使用&T
或&mut T
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.