在 Rust 中使用 return 语句和省略分号有什么区别? [英] What's the difference between using the return statement and omitting the semicolon in Rust?
问题描述
我正在编写一个函数,该函数在成功(和失败)时返回 serde_json::Value.以前在 Rust 中,我一直省略分号以从函数返回数据,如下面的代码示例所示:
I'm writing a function that returns a serde_json::Value upon success (and failure). Previously in Rust I have been omitting the semicolon to return data from a function, like in the code example below:
use serde_json::{Result, Value};
use core::result::Result as ResultCore;
fn returning_function() -> ResultCore<Value, Value> {
let data = r#"
{
"status": "ok",
"response": {
"data": "secret message!"
}
}
"#;
match str_to_json(data) {
Ok(json_data) => match json_data["status"].as_str() {
Some(status_str) => {
if status_str == "ok" {
Ok(json_data["response"].clone())
}
}
None => eprintln!("\"status\" was not a string")
}
Err(error) => eprintln!("something went wrong! here's what: {}", error)
}
Err(serde_json::Value::Null)
}
fn str_to_json(json_data: &str) -> Result<Value> {
Ok(serde_json::from_str(json_data)?)
}
这是我不明白的部分:这不能编译.Rust 的编译器告诉我类型不匹配",并且它期望类型 ()
,但 发现类型 serde_json::value::Value
.现在,我找到了一个可以编译的解决方案,如下所示:
Here comes the part I don't understand: this doesn't compile. Rust's compiler tells me "mismatched types", and that it expected type ()
, but found type serde_json::value::Value
. Now, I found a solution to this that does compile, and it is as follows:
use serde_json::{Result, Value};
use core::result::Result as ResultCore;
fn returning_function() -> ResultCore<Value, Value> {
let data = r#"
{
"status": "ok",
"response": {
"data": "secret message!"
}
}
"#;
match str_to_json(data) {
Ok(json_data) => match json_data["status"].as_str() {
Some(status_str) => {
if status_str == "ok" {
return Ok(json_data["response"].clone());
// ^ added return statement here
}
}
None => eprintln!("\"status\" was not a string")
}
Err(error) => eprintln!("something went wrong! here's what: {}", error)
}
Err(serde_json::Value::Null)
}
fn str_to_json(json_data: &str) -> Result<Value> {
Ok(serde_json::from_str(json_data)?)
}
通过添加return
语句,编译器突然高兴起来,编译器不再有任何可说的了.为什么是这样?我的印象是省略分号和使用 return 语句具有相同的含义——为什么这里不同?
By adding the return
statement the compiler suddenly is happy and the compiler doesn't have anything to say about it any more. Why is this? I was under the impression that omitting the semicolon and using the return statement had the same implications — why does it differ here?
推荐答案
return
语句,也称为提前返回,将从最后/最里面的类函数作用域返回一个对象.(类函数,因为它适用于闭包和函数)
A return
statement, otherwise known as an early return, will return an object from the last/innermost function-like scope. (Function-like because it applies to both closures and functions)
let x = || {
return 0;
println!("This will never happen!");
};
fn foo() {
return 0;
println!("This won't happen either");
}
一个不存在的分号将改为评估表达式,就像一个 return
,但只返回最后/最里面的作用域,或者换句话说,它从任何一组 {} 中返回代码>.
An absent semicolon will instead evaluate the expression, like a return
, but only return to the last/innermost scope, or in other words, it returns from within any set of {}
.
let x = { // Scope start
0
}; // Scope end
fn foo() -> usize { // Scope start
0
} // Scope end
return
语句会跳出任意数量的嵌套作用域,直到遇到类似函数的作用域:
return
statement will break out of any amount of nested scopes until it hits a function-like scope:
fn foo() -> usize {// <------------------------------------------\
{ // |
{ // |
{ // |
{ // |
{ // |
{ // |
{ // |
{ // |
{ // |
{ // |
{ // |
return 0; // ---/
}
}
}
}
}
}
}
}
}
}
}
}
return
语句也有自己的类型,也就是说 let x = return;
会实际编译.
The return
statement also has a type of its own, that is to say that let x = return;
will actually compile.
返回语句将评估为 !
,又名 从不输入.你现在不能用稳定锈命名它,但它最终会变得稳定和可用.
A return statement will evaluate to !
, AKA the never type. You can't name it in stable rust right now, but it will eventually become stable and usable.
这篇关于在 Rust 中使用 return 语句和省略分号有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!