我编写了以下代码来解析字符串以获取其中编码的整数,并使用match. 如果我得到一个Err(e)我想打印出错误e,并返回一个默认值。
return match t.parse::<usize>() {
Ok(n) => n,
Err(e) => {
println!("Couldn't parse the value for gateway_threads {}", e);
// Return two as a default value
return 2;
},
};
Run Code Online (Sandbox Code Playgroud)
然而,该代码无法编译,因为它需要类型()但得到一个整数:
return match t.parse::<usize>() {
Ok(n) => n,
Err(e) => {
println!("Couldn't parse the value for gateway_threads {}", e);
// Return two as a default value
return 2;
},
};
Run Code Online (Sandbox Code Playgroud)
如果我删除默认值的返回,我会收到错误expected usize but got `()`:
error[E0308]: mismatched types
--> src/main.rs:37:32
|
37 | return 2;
| ^ expected (), found integral variable
|
= note: expected type `()`
found type `{integer}
Run Code Online (Sandbox Code Playgroud)
完整代码(我正在解析 INI 配置文件以获取一些值):
extern crate threadpool;
extern crate ini;
use std::net::{TcpListener, TcpStream};
use std::io::Read;
use std::process;
use threadpool::ThreadPool;
use ini::Ini;
fn main() {
let mut amount_workers: usize;
let mut network_listen = String::with_capacity(21);
//Load INI
{
let conf: Ini = match Ini::load_from_file("/etc/iotcloud/conf.ini") {
Ok(t) => t,
Err(e) => {
println!("Error load ini file {}", e);
process::exit(0);
},
};
let section = match conf.section(Some("network".to_owned())) {
Some(t) => t,
None => {
println!("Couldn't find the network ");
process::exit(0);
},
};
//amount_workers = section.get("gateway_threads").unwrap().parse().unwrap();
amount_workers = match section.get("gateway_threads") {
Some(t) => {
return match t.parse::<usize>() {
Ok(n) => n,
Err(e) => {
println!("Couldn't parse the value for gateway_threads {}", e);
// Return two as a default value
return 2; //ERROR HERE;
},
};
},
None => 2, // Return two as a default value
};
let ip = section.get("bind_ip").unwrap();
let port = section.get("bind_port").unwrap();
network_listen.push_str(ip);
network_listen.push_str(":");
network_listen.push_str(port);
}
}
Run Code Online (Sandbox Code Playgroud)
导致此错误的原因是什么?
改变
amount_workers = match section.get("gateway_threads") {
Some(t) => {
return match t.parse::<usize>() {
Ok(n) => n,
Err(e) => {
println!("Couldn't parse the value for gateway_threads {}", e); //TODO: Log this
return 2; //ERROR HERE; //Default value is set to 2
}
};
}
None => 2, //Default value is set to 2
};
Run Code Online (Sandbox Code Playgroud)
到
amount_workers = match section.get("gateway_threads") {
Some(t) => {
match t.parse::<usize>() { // No return
Ok(n) => n,
Err(e) => {
println!("Couldn't parse the value for gateway_threads {}", e); //TODO: Log this
2 // No semicolon, no return
}
} // No semicolon
}
None => 2, //Default value is set to 2
};
Run Code Online (Sandbox Code Playgroud)
在 Rust 中,不以 结尾语句;是返回值的方式。return当您希望整个函数在最后一行之前返回一个值时,请使用该关键字,这就是您将其称为“早期返回”的原因 。
您可以在此处找到有关 Rust 如何处理表达式的更多信息。
| 归档时间: |
|
| 查看次数: |
4661 次 |
| 最近记录: |