文档
概念
函数

函数

NAPI-RS 中定义一个 JavaScript function 非常简单,只需要一个普通的 Rust fn

#[napi]
fn sum(a: u32, b: u32) -> u32 {
  a + b
}

最重要的是,你需要记住 NAPI-RS fn 并不支持所有的 Rust 类型, 下面的表格说明了在 fn 参数和返回类型里,JavaScript 类型和 Rust 类型的映射关系:

参数

Rust TypeJavaScript Type
u32number
i32number
i64number
f64number
boolboolean
Stringstring
Latin1Stringstring
UTF16Stringstring
#[napi(object)] structObject
& struct or &mut structClass instance
serde_json::MapObject
serde_json::Valueunknown
std::collections::HashMapObject
Arrayunknown[]
Vec<T> T must be types in this tableT[]
BufferBuffer
ExternalExternal (opens in a new tab)
Nullnull
Undefined / ()undefined
Option<T>T or null
Fn(Arg) ->T Arg and T must be types in this table(arg: Arg) => T
Promise<T>Promise<T>
AbortSignalAbortSignal (opens in a new tab)
JsSymbolSymbol
Int8Array / Uint8Array / Int16Array...TypedArray
BigIntBigInt

返回类型

Rust TypeJavaScript Type
u32number
i32number
i64number
f64number
boolboolean
Stringstring
Latin1Stringstring
UTF16Stringstring
#[napi(object)] structObject
#[napi] structClass
serde_json::MapObject
serde_json::Valueunknown
std::collections::HashMapObject
Arrayunknown[]
Vec<T> T must be types in this tableT[]
BufferBuffer
ExternalExternal
Nullnull
Undefined / ()undefined
Option<T>T or null
AsyncTask<Task<JsValue = T>>Promise<T>
JsSymbolSymbol
Int8Array / Uint8Array / Int16Array...TypedArray
BigIntBigInt
i64nBigInt
i128BigInt
u128BigInt