代码拉取完成,页面将自动刷新
use wasm_bindgen::prelude::*;
use js_sys::Date;
fn console_log(message: String) {
web_sys::console::log_1(&message.into());
}
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
let sum = 100000000;
return a + b + sum;
}
#[wasm_bindgen]
pub fn update_message(selector: &str, message: &str) {
let window = web_sys::window().expect("Failed to load window");
let document = window.document().expect("Failed to load document");
let element = document
.query_selector(selector)
.expect("Failed to load element");
if let Some(element) = element {
element.set_inner_html(message);
} else {
panic!("Failed to set inner html")
}
}
#[wasm_bindgen]
pub fn print_values(
js_number: i32,
js_number2: i32,
js_boolean: bool,
js_uint8_array: &[u8],
js_number_array: Vec<i32>,
) {
console_log(format!("js number: {}", js_number));
console_log(format!("js number: {}", js_number2));
console_log(format!("js boolean: {}", js_boolean));
for x in js_number..js_number2 {
console_log(format!("value is {}", x));
}
for item in js_uint8_array {
console_log(format!("js Uint8Array item: {}", item));
}
for item in js_number_array {
console_log(format!("js number array item: {}", item));
}
}
//Rust中提供了一个通用的类型——JsValue,可以作为任何JS类型
#[wasm_bindgen]
pub fn print_js_value(val: JsValue) {
console_log(format!("{:?}", val));
}
//使用Result返回报错
#[wasm_bindgen]
pub fn only_return_error_when_result(count: i32) -> Result<(), JsError> {
if count > 10 {
Ok(()) //返回为空
} else {
Err(JsError::new("count < 10"))
}
}
//使用Result返回正常值和错误
#[wasm_bindgen]
pub fn return_all_when_result(count: i32) -> Result<i32, JsError> {
if count > 10 {
Ok(count + 10)
} else {
Err(JsError::new("count < 10"))
}
}
#[wasm_bindgen]
pub fn return_time() -> f64 {
let date = Date::new_0();
date.get_time()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。