Member-only story

Difference between len() vs chars().count() in Rust

Newbie might misunderstand between them.

Donald Le
Jul 22, 2021
Photo by Kevin Lang on Unsplash

If you are coming from different languages like Python, you might guess that len() return the length of variable, if it is String, means the number of characters in it, but indeed it is not.

Instead String.len() return the bytes of that String.

If you want to get the number of characters in String, you need String.chars().count().

Take this snippet code for demonstration:

Running this code will show

The length of "ラウトは難しいです!" is 30.
The number of chars of "ラウトは難しいです!" is 10.

Hope it helps~~

~~PEACE~~

--

--

Donald Le
Donald Le

Written by Donald Le

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

No responses yet