2016-04-19 4 views
7

次のコードで、新しいオブジェクトの代わりにfloorの参照を返すにはどうすればよいですか?関数が借用参照または所有値のいずれかを返すことは可能ですか?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() 
    } 
} 

答えて

15

BigIntCloneを実装しているので、あなたは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) 
    } 
} 

後で、BigIntの所有するバージョンを取得、または単に参照としてそれを使用するCow::into_owned()を使用することができます。

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); 
    } 
} 
関連する問題