[SOLVED] Beginner, need help fixing slice example from the Rust book


I am a noob when it comes to programming in general, and Rust specifically.
I have arrived at chapter 4 by just figuring things out, but I noticed an oversight in one of the examples and wanted to fix it. First, about the code:

In the part about the slice type, there is an example to check the length of the first word in a string. I have added the fn main {...} part to make it usable and made it work with user input like in the guessing game example:

use std::io;

fn main() {

    let mut string = String::new();

        .read_line(&mut string)
        .expect("failed to read line");

    let length = first_word(&string);

    println!("The length of the first word of your input is {} characters.", length);

fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;


I noticed however, that there are two issues:

  1. If the first character in the string is a space, the length returned is 0, which is incorrect.
  2. If there is user input, there will be a newline character at the end, which will also falsify the length.

Both of these issues could be solved by using the trim() method on the string, but I get an error because it appears to change the type to &str instead of &String, at which point the first_word() function is not happy anymore.

What would be (an) elegant solution(s) to solving this?

Thank you in advance!

Okay, about 10 seconds after posting I figured it out. I don't know what I did wrong before, but it just works if I simply add let string = string.trim(); after reading the user input. It was that simple.

I hope this helps someone else though so I will not delete the issue :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.