在Rust中,是否可能返回已借用或拥有的类型?

14
在下面的代码中,我怎样才能返回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()
    }
}
1个回答

22

BigInt 实现了 Clone,因此您可以使用 std::borrow::Cow

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()来获取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);
}

5
在现实生活中,如果你借了一头牛,你应该把它归还给它的主人。 - cambunctious

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接