FIrst piece of code. Have a few questions

Hi there, I have been looking at Rust for some time, and I decided to have a look, learning it a little while also playing with WebAssembly, which is also an interesting subject for me.
I started with an example that I found in the documentation and I modified it a little, to get some basic concepts. This is what I have:

use std::rc::Rc;
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement, MouseEvent, Window};

pub fn start() {

	let window: Window = web_sys::window().unwrap();
	let document = window.document().unwrap();
	let canvas: HtmlCanvasElement = document

	let context: CanvasRenderingContext2d = canvas
	let blackRc: Rc<JsValue> = Rc::new(JsValue::from_str("#000000"));
	let whiteRc: Rc<JsValue> = Rc::new(JsValue::from_str("#FFFFFF"));
	draw(&context, &*whiteRc);

	let mut colorRc = whiteRc.clone();
    let closure = Closure::wrap(Box::new(move |_event: MouseEvent| {
		if Rc::ptr_eq(&colorRc, &blackRc) {
			colorRc = whiteRc.clone();
		else {
			colorRc = blackRc.clone();

		draw(&context, &*colorRc)
    }) as Box<dyn FnMut(_)>);
    canvas.add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref()).unwrap();

fn draw(context: &CanvasRenderingContext2d, color: &JsValue) {
	context.move_to(95.0, 75.0);

	// Draw the inner circle.
		.arc(75.0, 75.0, 20.0, 0.0, std::f64::consts::PI * 2.0)


Now, I have a few questions:

  • is the code correct? Any improvement I can make?
  • can we make this a little simpler? I think I have some problems with the fact that I have to clone those black and white things. It would be much easier if I could make them static, but I can't. Is there a reason why JsValue::from() is not static?
  • I tried 3 environments: Eclipse, IntelliJ, Visual Studio Code. Of this ones, only Visual Studio Code seems to have a working code completion. IntelliJ works somehow, Eclipse not at all (but I do have syntax highlighting). It seems to be related to web_sys.
    Is Visual Studio Code the only environment currently working properly?

Many thanks


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.