最近我阅读了Rust的文档,现在我决定使用web_sys API。我正在尝试使用Navigator::do_not_track
getter。。。嗯,更具体地说,我想打印返回值。根据文档,这是getter的签名:
pub fn do_not_track(&self) -> String
如果我理解正确,我应该能够使用format!
宏:
format!("{}", Navigator::do_not_track);
毫无疑问,我已经正确地导入了Navigator API。错误为:
error[E0277]: `for<'r> fn(&'r web_sys::features::gen_Navigator::Navigator) -> std::string::String {web_sys::features::gen_Navigator::Navigator::do_not_track}` doesn't implement `std::fmt::Display`
--> src/lib.rs:19:19
|
19 | format!("{}", Navigator::do_not_track);
| ^^^^^^^^^^^^^^^^^^^^^^^ `for<'r> fn(&'r web_sys::features::gen_Navigator::Navigator) -> std::string::String {web_sys::features::gen_Navigator::Navigator::do_not_track}` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `for<'r> fn(&'r web_sys::features::gen_Navigator::Navigator) -> std::string::String {web_sys::features::gen_Navigator::Navigator::do_not_track}`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required by `std::fmt::Display::fmt`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
如果我尝试使用web_sys::navigator
,我会得到
could not find "navigator" in "web_sys"
如何使用web_sys
访问web导航器API?
Navigator::do_not_track
是一个方法,这意味着需要首先检索类型为Navigator
的值。困惑的一个可能来源是找不到如何创建它
在启用DOM的JavaScript环境中,您会发现作为全局变量的大多数Web资源都可以通过Window
资源获得。您需要:
- 通过启用相应的Cargo功能,确保预期资源处于活动状态:
web_sys = { version = "0.3", features = ["Navigator, Window"] }
通过
web_sys::window
检索全局窗口,检查它是否可用。您最终可以通过一个可用的getter方法(
window.navigator()
(来检索所需的资源。
代码:
let window = web_sys::window().expect("Missing Window");
let navigator = window.navigator();
let do_not_track = navigator.do_not_track();
另请参阅:
wasm-bindgen
指南,其中还包括关于使用web-sys
的指南