2016-04-19 21 views
7

W poniższym kodzie jak mogę zwrócić referencję floor zamiast nowego obiektu? Czy jest możliwe, aby funkcja zwróciła pożyczoną referencję lub posiadaną wartość?Zwróć typ pożyczony lub posiadany w Rust

Cargo.toml

[dependencies] 
num = "0.1.32" 

main.rs

extern crate num; 
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() 
    } 
} 

Odpowiedz

15

Od BigInt implementuje Clone, można użyć std::borrow::Cow:

extern crate num; 

use num::bigint::BigInt; 
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) 
    } 
} 

Później można użyć Cow::into_owned() uzyskać własność wersję BigInt, lub po prostu użyć go jako odniesienie:

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