std-method

char::encode_utf8

Write one scalar to a caller-provided byte buffer and borrow only the resulting UTF-8 text. Four bytes suffice for any char. Expected stdout (not executed): ش 2 Common mistake: Passing an undersized buffer, which panics.

Formal Syntax & Structure

rust syntaxrust
fn encode_utf8(self, dst: &mut [u8]) -> &mut str

Working Example

Example Snippetrust
fn main() {    let mut buffer = [0; 4];    let text = 'ش'.encode_utf8(&mut buffer);    println!("{text} {}", text.len());}
Rust Reference