Rust 是否可以归还借来的或拥有的锈迹类型?
在下面的代码中,如何返回Rust 是否可以归还借来的或拥有的锈迹类型?,rust,ownership,Rust,Ownership,在下面的代码中,如何返回floor的引用而不是新对象?是否可以让函数返回借用的引用或拥有的值 extern crate num; // 0.2.0 use num::bigint::BigInt; fn cal(a: BigInt, b: BigInt, floor: &BigInt) -> BigInt { let c: BigInt = a - b; if c.ge(floor) { c } else { floor.
floor
的引用而不是新对象?是否可以让函数返回借用的引用或拥有的值
extern crate num; // 0.2.0
use num::bigint::BigInt;
fn cal(a: BigInt, b: BigInt, floor: &BigInt) -> BigInt {
let c: BigInt = a - b;
if c.ge(floor) {
c
} else {
floor.clone()
}
}
由于
BigInt
实现了Clone
,因此可以使用:
在现实生活中,如果你有一头借来的牛,你应该把它还给它的主人。
use num::bigint::BigInt; // 0.2.0
use std::borrow::Cow;
fn cal(a: BigInt, b: BigInt, floor: &BigInt) -> Cow<BigInt> {
let c: BigInt = a - b;
if c.ge(floor) {
Cow::Owned(c)
} else {
Cow::Borrowed(floor)
}
}
fn main() {
let a = BigInt::from(1);
let b = BigInt::from(2);
let c = &BigInt::from(3);
let result = cal(a, b, c);
let ref_result = &result;
println!("ref result: {}", ref_result);
let owned_result = result.into_owned();
println!("owned result: {}", owned_result);
}