【问题标题】:Is it possible to return either a borrowed or owned type in Rust?是否可以在 Rust 中返回借用或拥有的类型?
【发布时间】:2016-08-10 22:13:16
【问题描述】:

在以下代码中,如何返回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()
    }
}

【问题讨论】:

    标签: rust ownership


    【解决方案1】:

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

    【讨论】:

    • 在现实生活中,如果你有一头借来的牛,你应该把它还给它的主人。
    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2014-12-22
    相关资源
    最近更新 更多