WASM/RUST/DOM compile failed

I try to compile this code (I am new to Rust and WASM) with this:

wasm-pack build --target web
[INFO]: :dart: Checking for the Wasm target...
[INFO]: :cyclone: Compiling to Wasm...
Compiling hello-wasm v0.1.0 (/Users/laplante/rust/hello-wasm)
error[E0599]: no method named set_text_content found for enum Result in the current scope
--> src/lib.rs:18:9
|
18 | val.set_text_content(Some("Hello from Rust!"));
| ^^^^^^^^^^^^^^^^ method not found in Result<Element, JsValue>

error[E0308]: mismatched types
--> src/lib.rs:20:23
|
20 | body.append_child(&val);
| ^^^^ expected struct Node, found enum Result
|
= note: expected reference &Node
found reference &Result<Element, JsValue>

Some errors have detailed explanations: E0308, E0599.
For more information about an error, try rustc --explain E0308.
error: could not compile hello-wasm due to 2 previous errors
Error: Compiling your crate to WebAssembly failed
Caused by: failed to execute cargo build: exited with exit status: 101
full command: "cargo" "build" "--lib" "--release" "--target" "wasm32-unknown-unknown"

The code is:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern {
    pub fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) {
    alert(&format!("Hello, {}!", name));

    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let body = document.body().expect("document should have a body");

    // Manufacture the element we're gonna append
    let val = document.create_element("p");
    val.set_text_content(Some("Hello from Rust!"));

    body.append_child(&val);
}

Document::create_element returns Result, so you have to handle the error case somehow. In this code, it's probably possible to just unwrap it. In more general case, it'd be useful to understand the corresponding chapter of the Book.

2 Likes

I find this here (web_sys::Document::create_element function)
and it's working

		let val = document.create_element("p").unwrap();
		val.set_inner_html("Hello World from WebAssemblyMan!");
		body.append_child(&val).unwrap();

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.