简体   繁体   中英

Rust - How can I return multiple variables from a function such that they are accessible outside the scope the function is called in?

I want to call a function if a condition is met and return multiple values that will be used outside the scope of the conditional block. If the function were only to return one value I would declare the variable at an appropriate earlier point, but as far as I can tell Rust does not allow for assignment of multiple variables unless these variables are also being declared.

Is there a way around this?

Here's some pseudo-code to illustrate my question:

 // This approach doesn't work for scope reasons

fn function(inp1, inp2) {
    calculate results;
    (var_a, var_b, var_c)
}

fn main() {
    
    let state = true;
    
    if state == true {
        let (var_a, var_b, var_c) = function(input_1, input_2);
    }
    
    do something with var_a, var_b, and var_c;
    
}
// This approach works when returning one variable

fn function(inp1, inp2) {
    calculate results;
    var_a
}

fn main() {

    let var_a;
    
    let state = true;
    
    if state == true {
        var_a = function(input_1, input_2);
    }
    
    do something with var_a;
    
}

In general you can use that approach to solve it (note commented if statement, explained below):

fn function() -> (i32, i32) {
    return (42, 54);
}

fn main() {
    
    //let state = true;
    
    let v: (i32, i32);
    //if state == true {
    {
        v = function();
    }
    
    let (var_a, var_b) = v;
    println!("a:{} b:{}", var_a, var_b);
    
}

If you would like to keep the if in place then else branch should be provided as well. Otherwise there will be an error like:

error[E0381]: use of possibly-uninitialized variable: `v`
  --> src/main.rs:16:10
   |
16 |     let (var_a, var_b) = v;
   |          ^^^^^ use of possibly-uninitialized `v.0`

That error don't have any relation with "returning a tuple". The same error come even for the provided 'one variable' example ( playground ).

The final solution may looks like:

fn function() -> (i32, i32) {
    return (42, 54);
}

const DEFAULT: (i32, i32) = (0, 0);

fn main() {
    
    let state = true;
    
    let v: (i32, i32);
    if state == true {
        v = function();
    } else {
        v = DEFAULT;
    }
    
    let (var_a, var_b) = v;
    println!("a:{} b:{}", var_a, var_b);
    
}

PS I personally prefer to move the state 's check inside the function to simplify the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM