一个 Rust 文件
Rust 文件的导入方式和头文件一样。pub fn 是函数,带有 impl 的 pub struct 是类。
units.rs 是纯 Rust,没有属性(attribute),也没有绑定代码。Celsius::new 是构造函数,snake_case 的名称会变成 camelCase:word_count 变为 wordCount,to_fahrenheit 变为 toFahrenheit。
C++ 和 Rust 文件可以并存于同一个项目中,一次 initNative() 就能启动两者。Rust 课程会继续介绍集合、Option 和 Result。
[■]units.rs1// A pub fn is a function in JavaScript, and a pub struct with
// its impl is a class. snake_case names arrive in camelCase.
pub fn word_count(text: &str) -> i32 {
text.split_whitespace().count() as i32
}
pub struct Celsius {
degrees: f64,
}
impl Celsius {
pub fn new(degrees: f64) -> Self {
Celsius { degrees }
}
pub fn to_fahrenheit(&self) -> f64 {
self.degrees * 9.0 / 5.0 + 32.0
}
}
[■]main.js2import {
initNative, wordCount, Celsius,
} from './native/units.rs';
await initNative();
console.log('words:', await wordCount('import a Rust file'));
const today = await new Celsius(21.5);
console.log('in Fahrenheit:', await today.toFahrenheit());
在 C++、Rust、包或导入发生变化之前,无需编译即可运行。
[■]输出按“运行”或 Ctrl+Enter 运行 main.js。