集合与字节
Rust 集合会以普通 JavaScript 值的形式传递:Vec 是数组,以字符串为键的 map 是对象,字节则是 Uint8Array。
sorted 接受一个数组并返回一个数组,word_lengths 返回一个 BTreeMap,它会变成以其字符串为键的对象。每一个都是深拷贝:JavaScript 和 Rust 之间不共享任何集合。
invert 从 Uint8Array 中读取它的 &[u8],并返回一个 Vec<u8>,后者会变成一个新的 Uint8Array。&[f64] 和 Vec<f64> 也以同样的方式传递,变成 Float64Array。
试一试
对另一个列表排序,然后把反转后的字节再反转一次,得到最初的数组。[■]data.rs1use std::collections::BTreeMap;
// A Vec arrives as an array, and a map with string keys as an
// object. Bytes cross as a Uint8Array, both ways.
pub fn sorted(mut words: Vec<String>) -> Vec<String> {
words.sort();
words
}
pub fn word_lengths(text: &str) -> BTreeMap<String, i32> {
text.split_whitespace()
.map(|word| (word.to_string(), word.len() as i32))
.collect()
}
pub fn invert(bytes: &[u8]) -> Vec<u8> {
bytes.iter().map(|byte| 255 - byte).collect()
}
[■]main.js2import {
initNative, sorted, wordLengths, invert,
} from './native/data.rs';
await initNative();
console.log(await sorted(['pear', 'apple', 'fig']));
console.log(await wordLengths('import a Rust file'));
console.log([...await invert(new Uint8Array([0, 64, 255]))]);