在下面的代码中,如何返回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()
}
}
Since BigInt
实施Clone
,你可以使用std::borrow::Cow https://doc.rust-lang.org/std/borrow/enum.Cow.html:
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)
}
}
稍后您可以使用Cow::into_owned() https://doc.rust-lang.org/std/borrow/enum.Cow.html#method.into_owned获得拥有的版本BigInt
,或者只是将其用作参考:
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)