2016-04-19 21 views
7

Nel seguente codice, come posso restituire il riferimento di floor anziché un nuovo oggetto? È possibile consentire alla funzione di restituire un riferimento preso in prestito o un valore di proprietà?Restituire un tipo preso in prestito o di proprietà in 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() 
    } 
} 

risposta

15

Dal BigInt concretizzazione Clone, è possibile utilizzare un 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) 
    } 
} 

Successivamente, è possibile utilizzare Cow::into_owned() per ottenere una versione di proprietà di BigInt, o semplicemente utilizzarlo come punto di riferimento:

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