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

喜夏-厌秋 提交于 2019-11-26 11:37:48

问题


In the following code, how can I return the reference of floor instead of a new object? Is it possible to let the function return either a borrowed reference or an owned value?

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:


Since BigInt implements Clone, you can use a 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)
    }
}

Later, you can use Cow::into_owned() to get a owned version of BigInt, or just use it as a reference:

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


来源:https://stackoverflow.com/questions/36706429/is-it-possible-to-return-either-a-borrowed-or-owned-type-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!