Tag Archives: rust

Rust: You probably meant to use .chars().count()

After reading a fantastic article by Ian Whitney, it came to my attention that there is some confusion regarding the “length” of a string in Rust. According to the documentationstd::string::String.len() returns the number of bytes that are in the given string. On a technical level, there is nothing confusing about this definition. However, it is widely accepted by other languages (like Java and Ruby) that the “length” of a string is the number of characters within the string.

The problem with this difference in definition is brought to light in a playpen by respeccing which shows that Rust’s std::String::String.len() function produces counter-intuitive results. Two strings with the same character count return different “lengths” because they contain a different number of bytes.

The solution to this is instead to use a String’s character iterator and count the number of elements, as std::string::String.chars().count() does.

Reddit Discussion

Using Variable Bindings as Array Indices in Rust

Today marks the first day that I’ve begun my journey with Rust 1.0. So far, I’m loving it. However, there are some parts that can be very confusing.

While trying to make a simple Tic-Tac-Toe game, I came across a problem where I could not find the correct type for array indices. I wasn’t sure where to look in the documentation, but I ended up finally finding the solution. If you were wondering, array indices must be of type usize. Here is the code example I was using for reference,

let mut answer = String::new();                                             
io::stdin().read_line(&mut answer)                                          
     .ok()                                                                   
    .expect("Error reading line");                                          
                                                                             
let answer:usize = match answer.trim().parse() {                            
     Ok(num) => num,                                                         
     Err(_) => 0,                                                            
 };                                                                          
                                                                               
 board = 'X';