ECMAScript 安全赋值运算符 (?=) 提案介绍及其 Polyfill
本文介绍最新的 ECMAScript 安全赋值运算符提案以及相应的替代实现前言
我们经常会跟 try/catch 打交道,但如果你写过 Go 或者 Rust 就会发现在这两种语言中是没有 try/catch 的,那么这些语言怎么进行错误捕获呢
[*]Go: Error handling
f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
}
// do something with the open *File f
[*]Rust: ? Operator / Result Type
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"));
}
[*]Swift: try? Operator
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")
[*]Zig: try Keyword
const parseU64 = @import("error_union_parsing_u64.zig").parseU64;
fn doAThing(str: []u8) !void {
const number = try parseU64(str, 10);
_ = number; // ...
}好了,以上例子仅用于体现 JavaScript 语法的简单(笑
不过也确实写 try/catch 嵌套写烦了,偶然发现了这个 ?= 提案,眼前一亮,真的简洁直观
来源:https://www.cnblogs.com/himeka/p/18544502
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]