【发布时间】:2020-08-17 02:55:59
【问题描述】:
上下文:我正在学习 Rust 和 WebAssembly,作为一个练习练习,我有一个项目,它用 Rust 代码在 HTML Canvas 中绘制东西。我想从网络请求中获取查询字符串,然后代码可以决定调用哪个绘图函数。
我编写这个函数只是为了返回删除了前导 ? 的查询字符串:
fn decode_request(window: web_sys::Window) -> std::string::String {
let document = window.document().expect("no global window exist");
let location = document.location().expect("no location exists");
let raw_search = location.search().expect("no search exists");
let search_str = raw_search.trim_start_matches("?");
format!("{}", search_str)
}
它确实有效,但考虑到在我使用的其他一些语言中它会简单得多,它似乎非常冗长。
有没有更简单的方法来做到这一点?或者冗长只是你为 Rust 的安全性付出的代价,我应该习惯它?
根据@IInspectable 的回答进行编辑: 我尝试了链接方法,但出现以下错误:
temporary value dropped while borrowed
creates a temporary which is freed while still in use
note: consider using a `let` binding to create a longer lived value rustc(E0716)
如果能更好地理解这一点,那就太好了;我仍然通过我的头脑获得所有权的细节。现在是:
fn decode_request(window: Window) -> std::string::String {
let location = window.location();
let search_str = location.search().expect("no search exists");
let search_str = search_str.trim_start_matches('?');
search_str.to_owned()
}
这当然是一种改进。
【问题讨论】:
标签: rust wasm-bindgen rust-wasm