-3

i tried the program myself, but this error is coming below :-

    1156 |   let user = replace_vowels(&word);
     |       ^^^^ doesn't have a size known at compile-time
     |
     = help: the trait `Sized` is not implemented for `str`
     = note: all local variables must have a statically known size
     = help: unsized locals are gated as an unstable feature

error[E0277]: the size for values of type `str` cannot be known at compilation time
    --> src/main.rs:1157:33
     |
1157 |   println!("the new word is {}",user);
     |                                 ^^^^ doesn't have a size known at compile-time
     |
     = help: the trait `Sized` is not implemented for `str`
note: required by a bound in `ArgumentV1::<'a>::new_display`
     = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

the program is :-

fn main(){
  let word: &str = "hello";
  let user = replace_vowels(&word);
  println!("the new word is {}",user);
}

fn replace_vowels(w : &str) -> str{
  let vowel_lst = ["a","e","i","o","u"];
  for mut i in w.iter(){
    if i == "a" || i == "e" || i == "o" || i == "i" || i == "u"{
      i = "*";
    }
  }
  w
}

can someone help me to rectify this error? i dont know whether i did mistake in references or something?

Mario Santini
  • 2,905
  • 2
  • 20
  • 27
dave j
  • 1
  • 1
  • 4
  • Better to focus the question on the technical problem you encountered instead of the kind of program you were trying to write when you encountered it. (And if you search for other questions about that same problem, you may discover it to be already asked and answered) – Charles Duffy May 17 '22 at 13:15
  • 1
    If you want to modify the string in place, as your code indicates, you should accept an `&mut str` as parameter and return nothing at all – the mutable string slice will be changed in place, so there is not need to return anything. If you instead want to return a new string, you should accept a `&str` and return a `String`. See also [What are the differences between Rust's `String` and `str`?](https://stackoverflow.com/questions/24158114/what-are-the-differences-between-rusts-string-and-str) – Sven Marnach May 17 '22 at 13:29
  • yes this link answered my question. thank you!! – dave j May 17 '22 at 14:11

1 Answers1

1

One ideomatic way is to deconstruct the &str into its chars iterator, then map a closure that would return the character if is not matching the criteria otherwise would return the same char, finally collect it into the final type (an owned String):

fn replace_vowels(w: &str) -> String {
    w.chars()
        .map(|i| {
            if i == 'a' || i == 'e' || i == 'o' || i == 'i' || i == 'u' {
                '*'
            } else {
                i
            }
        })
        .collect()
}

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93