本文介绍最新的 ECMAScript 安全赋值运算符提案以及相应的替代实现
前言
我们经常会跟 try/catch
打交道,但如果你写过 Go 或者 Rust 就会发现在这两种语言中是没有 try/catch
的,那么这些语言怎么进行错误捕获呢
f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
}
// do something with the open *File f
use std::num::ParseIntError;
fn multiply(first_number_str: &str, second_number_str: &str) -> Result<i32, ParseIntError> {
let first_number = first_number_str.parse::<i32>()?;
let second_number = second_number_str.parse::<i32>()?;
Ok(first_number * second_number)
}
fn print(result: Result<i32, ParseIntError>) {
match result {
Ok(n) => println!("n is {}", n),
Err(e) => println!("Error: {}", e),
}
}
fn main() {
print(multiply("10", "2"));
print(multiply("t", "2"));
}
func fetchData() -> Data? {
if let data = try? fetchDataFromDisk() { return data }
if let data = try? fetchDataFromServer() { return data }
return nil
}
let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")
const parseU64 = @import("error_union_parsing_u64.zig").parseU64;
fn doAThing(str: []u8) !void {
const number = try parseU64(str, 10);
_ = number; // ...
}
好了,以上例子仅用于体现 JavaScript 语法的简单(笑
不过也确实写 try/catch 嵌套写烦了,偶然发现了这个 ?=
提案,眼前一亮,真的简洁直观