簡體   English   中英

Rust - 如何從函數返回多個變量,以便在調用函數的范圍之外可以訪問它們?

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

如果滿足條件,我想調用一個函數並返回將在條件塊范圍之外使用的多個值。 如果函數只返回一個值,我會在適當的較早時間聲明該變量,但據我所知,Rust 不允許分配多個變量,除非這些變量也被聲明。

有沒有解決的辦法?

這是一些偽代碼來說明我的問題:

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

一般來說,您可以使用該方法來解決它(注意注釋if語句,解釋如下):

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 ,則還應提供else分支。 否則會出現如下錯誤:

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`

該錯誤與“返回元組”沒有任何關系。 即使對於提供的“一個變量”示例( playground ),也會出現相同的錯誤。

最終的解決方案可能如下所示:

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 我個人更喜歡將state的檢查移動到function內部以簡化代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM