[英]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.如果函数只返回一个值,我会在适当的较早时间声明该变量,但据我所知,Rust 不允许分配多个变量,除非这些变量也被声明。
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):一般来说,您可以使用该方法来解决它(注意注释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 you would like to keep the if
in place then else
branch should be provided as well.如果您想保留if
,则还应提供else
分支。 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 ).即使对于提供的“一个变量”示例( 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. PS 我个人更喜欢将state
的检查移动到function
内部以简化代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.