是否可以在 Rust 中返回借用或拥有的类型? [英] Is it possible to return either a borrowed or owned type in Rust?

查看:45
本文介绍了是否可以在 Rust 中返回借用或拥有的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

由于 BigInt 实现了 Clone,您可以使用 std::borrow::Cow:

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

稍后,您可以使用 Cow::into_owned() 获取 BigInt 的拥有版本,或仅将其用作参考:

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

这篇关于是否可以在 Rust 中返回借用或拥有的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆