String

T parameter&T parameter&mut T parameterT return valueOption<T> parameterOption<T> return valueJavaScript representation
YesNoNoYesYesYesJavaScript string value

Copies the string's contents back and forth between the JavaScript garbage-collected heap and the Wasm linear memory with TextDecoder and TextEncoder

Note: Be sure to check out the documentation for str to learn about some caveats when working with strings between JS and Rust.

Example Rust Usage

#![allow(unused)]
fn main() {
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<String>) {}

#[wasm_bindgen]
pub fn return_option_string() -> Option<String> {
    None
}
}

Example JavaScript Usage

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"
}