JavaScript (Node.js) and Rust, side by side
length and slice count UTF-16 code units, so truncating emoji keeps half a surrogate pair.const word = "café";
const thumbs = "👍";
console.log(word.length, thumbs.length, [...thumbs].length);
console.log(Buffer.byteLength(word), Buffer.byteLength(thumbs));
function truncate(text, max) {
return text.length <= max ? text : text.slice(0, max - 1) + "…";
}
console.log(truncate("👍👍👍", 2)); // keeps half a surrogate pairget(0..4) is None because byte 4 falls inside é.fn truncate(text: &str, max: usize) -> String {
if text.chars().count() <= max {
return text.to_string();
}
let kept: String = text.chars().take(max.saturating_sub(1)).collect();
kept + "…"
}
fn main() {
let word = "café";
let thumbs = "👍";
println!("{} {} {}", word.len(), thumbs.len(), thumbs.chars().count());
println!("{:?}", word.get(0..4));
println!("{}", truncate("👍👍👍", 2));
}| JavaScript (Node.js) | Rust |
|---|---|
"café".length is 4 UTF-16 code units. | "café".len() is 5 UTF-8 bytes, and chars().count() is 4. |
"👍".length is 2: a surrogate pair. | "👍".len() is 4 and "👍".chars().count() is 1. |
text[0] returns the first code unit, possibly half a character. | text[0] does not compile; use text.chars().next(). |
slice(0, n) can cut a surrogate pair in half. | &text[..n] panics off a character boundary, and text.get(..n) returns None. |
Understand it
A JavaScript string is a sequence of UTF-16 code units. "café".length is 4, but "👍".length is 2, because the emoji needs a surrogate pair, while [..."👍"].length is 1 because the string iterator walks code points. Indexing and slice work on code units, so "👍👍👍".slice(0, 1) returns half a character and the truncated output prints a replacement character.
A Rust String, like a borrowed &str, is UTF-8. len() is the byte length: "café".len() is 5 because é takes two bytes, and "👍".len() is 4. chars() yields char values, which are Unicode scalar values, so "👍".chars().count() is 1. Neither number counts characters as a reader sees them: "👍🏽" is one grapheme but two scalar values, and grapheme segmentation needs a crate such as unicode-segmentation.
Because a byte offset may fall inside a character, text[0] does not compile at all. Slicing by a byte range is allowed but panics if a bound is not on a character boundary, while text.get(0..4) returns None instead. For the first character use text.chars().next(), and for the first n characters text.chars().take(n).collect::<String>().
Case conversion works on characters too. char::to_uppercase returns an iterator because one character can become several: ß becomes SS, the same answer JavaScript's toUpperCase gives. flat_map(char::to_uppercase) collects them all.
The JavaScript (Node.js) habit, written in Rust
This is how the JavaScript (Node.js) version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.
fn main() {
let word = String::from("café");
let first = word[0];
println!("{first}");
}Try it
Port the JavaScript initials shown at the top of solution.rs. Take the first character of each whitespace-separated word and uppercase it, without byte indexing, so names such as élodie durand and 𝒜da lovelace work. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.
What success looks like: The local compiler accepts the changed solution and the separate verification harness passes every case, including accented and non-BMP initials, ß and extra spaces. Printing a success message alone does not complete this lab.
Check your understanding
What does "café".len() return in Rust, where JavaScript's "café".length is 4?
Reveal the answer
4, the number of characters5, the number of UTF-8 bytes8, the number of UTF-16 bytes
len() is the byte length of the UTF-8 encoding. é (U+00E9) takes two bytes, so the total is 5.
Go deeper
Common misconception: “len() is the number of characters, like .length.”
len() counts UTF-8 bytes. Count Unicode scalar values with chars().count(), and remember that even that is not a count of user-perceived characters.
- Measure three ways:
"café"has 4 scalar values and 5 UTF-8 bytes; JavaScript reports 4 UTF-16 code units."👍"has 1 scalar value, 4 bytes and 2 code units. - Check the slice:
word.get(0..4)asks for bytes 0 to 3. Byte 3 is the first of the two bytes ofé, so the range would split a character andgetreturnsNone. - Compare with evidence: Run it:
5 4 1,None, then👍…. JavaScript'struncateprinted a replacement character because it kept half a surrogate pair.
Transfer challenge: Print "👍🏽".len(), "👍🏽".chars().count() and the chars themselves with {:?}. Then predict JavaScript's "👍🏽".length and [..."👍🏽"].length before you check them in Node.
Connections
- Objects and Map vs HashMap: Keyed data with HashMap and entry
- Shared references vs ownership: Moves instead of shared references

Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: UTF-16 strings vs UTF-8 String (courseId "rust-for-nodejs-developers", lessonId "node-utf16-strings-to-utf8") Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-utf16-strings-to-utf8/ Goal: len() counts UTF-8 bytes and chars().count() counts Unicode scalar values; neither counts graphemes, and a String cannot be indexed by position. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-utf16-strings-to-utf8) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.