[WASM + Rust] Debug a WebAssembly Module Written in Rust using console.log

本文介绍如何使用Rust的wasm_bindgen库调用JavaScript的console.log函数,实现从Rust中输出日志信息。通过定义一个Rust风格的println!宏,我们可以在Rust代码中轻松地使用JavaScript的浏览器开发者工具进行调试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Having some kind of debugging tool in our belt is extremely useful before writing a lot of code. In this lesson we build a println!()-style syntax using JavaScript’s console.log to be able to log out values in Rust.

 
n JavaScript, the console log function is the way to log messages to the browser's developer tool console. Using Rust wasm_bindgen , we can import a reference to it.
 
extern "C" {
    ...
    #[wasm_bindgen(js_namespace = console)]
    fn log(msg: &str);
}

 

Using the Rust macro, we can provide a inaudible style syntax for console log, logging from Rust.

#[wasm_bindgen]
pub fn run() {
    let val = document.createElement("p");
    log!("The {} is {}", "meaning of life", 42);
    val.set_inner_html("Hello from Rust!!!!!!");
    document.body().append_child(val);
}

 

Reload the server, then in the broswer console, we can see the console.log message from Rust.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值