Rust ファイル
Rust ファイルはヘッダーファイルと同じようにインポートされます。pub fn は関数に、pub struct とその impl はクラスになります。
units.rs は属性もバインディングのコードもない、通常の Rust です。Celsius::new がコンストラクターになり、snake_case の名前は camelCase で届きます。word_count は wordCount に、to_fahrenheit は toFahrenheit になります。
C++ と Rust のファイルは 1 つのプロジェクトに並べて置け、1 回の initNative() で両方が起動します。Rust のレッスンでは、続けてコレクション、Option、Result を扱います。
試してみる
別の文の単語を数え、37 度を変換してみましょう。[■]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 を実行します。