gpt4 book ai didi

vector - Rust - 如何从函数返回多个变量,以便在调用函数的范围之外可以访问它们?

转载 作者:行者123 更新时间:2023-12-03 11:29:41 36 4
gpt4 key购买 nike

如果满足条件,我想调用一个函数并返回将在条件块范围之外使用的多个值。如果函数只返回一个值,我会在适当的较早时间声明该变量,但据我所知,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 ),也会出现相同的错误。
final solution可能看起来像:
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);

}
附言我个人更喜欢移动 statefunction 里面的检查以简化代码。

关于vector - Rust - 如何从函数返回多个变量,以便在调用函数的范围之外可以访问它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64187012/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com