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

时间:2016-04-19 00:21:06

标签: 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.clone()
    }
}

1 个答案:

答案 0 :(得分:17)

由于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);
}