是否可以 return 在 Rust 中借用或拥有的类型?

Is it possible to return either a borrowed or owned type in Rust?

在下面的代码中,如何 return 引用 floor 而不是新对象?是否可以让函数 return 成为借用的引用或拥有的值?

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,您可以使用 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);
}