Rust 有没有办法简化对web_sys内部功能的访问?
在阅读了《铁锈》一书之后,我决定尝试一下Web组装。我正在创建一个简单的跟踪器脚本来练习和了解它。有两种方法需要访问窗口、导航器或CookieAPI。每次我必须访问其中任何一个,都会涉及很多锅炉铭牌代码:Rust 有没有办法简化对web_sys内部功能的访问?,rust,global-variables,webassembly,Rust,Global Variables,Webassembly,在阅读了《铁锈》一书之后,我决定尝试一下Web组装。我正在创建一个简单的跟踪器脚本来练习和了解它。有两种方法需要访问窗口、导航器或CookieAPI。每次我必须访问其中任何一个,都会涉及很多锅炉铭牌代码: pub fn start() { let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let html = document.dy
pub fn start() {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let html = document.dyn_into::<web_sys::HtmlDocument>().unwrap();
let cookie = html_document.cookie().unwrap();
}
但编译失败,原因是:*mut u8
无法在线程之间安全共享”
那是不切实际的,让我很烦恼
不确定您的问题是什么,但是如果您在应用程序中反复访问同一个cookie,也许您可以将其保存在一个结构中并使用该结构?在我最近的WebAssembly项目中,我保存了在结构中使用的一些元素,并通过传递它们来使用它们
我还认为,解释您的特定用例可能会得到更具体的答案:)您可以使用
?
操作符而不是展开
而不是写作
pub fn start() {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let html = document.dyn_into::<web_sys::HtmlDocument>().unwrap();
let cookie = html_document.cookie().unwrap();
}
如果您发现不喜欢频繁重复此操作,则可以使用函数
fn document() -> Result<Document> {
web_sys::window()?.document()
}
fn html() -> Result<web_sys::HtmlDocument> {
document()?.dyn_into<web_sys::HtmlDocument>()
}
fn cookie() -> Result<Cookie> {
html()?.cookie()
}
pub fn start() {
let cookie = cookie()?;
}
fn document()->结果{
web_sys::window()?.document()
}
fn html()->结果{
document()?.dyn_into()
}
fn cookie()->结果{
html()?.cookie()
}
发布fn开始(){
设cookie=cookie()?;
}
什么都没有?真的吗?只是使用函数fn html()->HtmlDocument{let window=web\u sys::window().unwrap();let document=window.document().unwrap();document.dyn\u into::().unwrap()}
一点补充:在任何地方使用unwrap可能是一种不好的做法。请尝试处理错误,或者至少使用.expect(),这样您就可以提供有意义的错误消息,而不是尝试在…上调用unwrap
pub fn start() -> Result<()> {
let cookie = web_sys::window()?
.document()?
.dyn_into<web_sys::HtmlDocument>()?
.cookie()?;
Ok(())
}
pub fn start() {
let cookie = (|| Result<Cookie)> {
web_sys::window()?
.document()?
.dyn_into<web_sys::HtmlDocument>()?
.cookie()
}).unwrap();
}
fn document() -> Result<Document> {
web_sys::window()?.document()
}
fn html() -> Result<web_sys::HtmlDocument> {
document()?.dyn_into<web_sys::HtmlDocument>()
}
fn cookie() -> Result<Cookie> {
html()?.cookie()
}
pub fn start() {
let cookie = cookie()?;
}