diff --git a/examples/guide-supported-types-examples/src/lib.rs b/examples/guide-supported-types-examples/src/lib.rs index f0f83f8e..de7d6ac5 100755 --- a/examples/guide-supported-types-examples/src/lib.rs +++ b/examples/guide-supported-types-examples/src/lib.rs @@ -6,3 +6,4 @@ extern crate wasm_bindgen; pub mod imported_types; pub mod exported_types; pub mod str; +pub mod string; diff --git a/examples/guide-supported-types-examples/src/string.rs b/examples/guide-supported-types-examples/src/string.rs new file mode 100644 index 00000000..f9f3e5c9 --- /dev/null +++ b/examples/guide-supported-types-examples/src/string.rs @@ -0,0 +1,17 @@ +use wasm_bindgen::prelude::*; + +#[wasm_bindgen] +pub fn take_string_by_value(x: String) {} + +#[wasm_bindgen] +pub fn return_string() -> String { + "hello".into() +} + +#[wasm_bindgen] +pub fn take_option_string(x: Option) {} + +#[wasm_bindgen] +pub fn return_option_string() -> Option { + None +} diff --git a/examples/guide-supported-types-examples/string.js b/examples/guide-supported-types-examples/string.js new file mode 100644 index 00000000..4c9defcd --- /dev/null +++ b/examples/guide-supported-types-examples/string.js @@ -0,0 +1,22 @@ +import { + take_string_by_value, + return_string, + take_option_string, + return_option_string, +} from './guide_supported_types_examples'; + +take_string_by_value('hello'); + +let s = return_string(); +console.log(typeof s); // "string" + +take_option_string(null); +take_option_string(undefined); +take_option_string('hello'); + +let t = return_option_string(); +if (t == null) { + // ... +} else { + console.log(typeof s); // "string" +} diff --git a/guide/src/reference/types.md b/guide/src/reference/types.md index 64659ca0..210a17fa 100644 --- a/guide/src/reference/types.md +++ b/guide/src/reference/types.md @@ -73,6 +73,18 @@ Copies the string's contents back and forth between the JavaScript garbage-collected heap and the Wasm linear memory with `TextDecoder` and `TextEncoder` +### Example Rust Usage + +```rust +{{#include ../../../examples/guide-supported-types-examples/src/string.rs}} +``` + +### Example JavaScript Usage + +```js +{{#include ../../../examples/guide-supported-types-examples/string.js}} +``` + ## `char` | `T` parameter | `&T` parameter | `&mut T` parameter | `T` return value | `Option` parameter | `Option` return value | JavaScript representation |