1

I am trying to make a function in Rust that returns a string vector. This is what I have so far:

fn letters() -> Vec<String> {
    let mut v = Vec::new();
    v.push("a");
    v.push("b");
    v
}
fn main() {
    println!("{:?}", letters());
}

This is the error:

error[E0308]: mismatched types
 --> src/main.rs:5:5
  |
1 | fn letters() -> Vec<String> {
  |                 ----------- expected `Vec<String>` because of return type
...
5 |     v
  |     ^ expected struct `String`, found `&str`
  |
  = note: expected struct `Vec<String>`
             found struct `Vec<&str>`

I have been struggling with this. It seems that the only way I can solve the problem is by declaring the vector in a different way but I need to declare it the way I did.

trent
  • 25,033
  • 7
  • 51
  • 90
  • Welcome to Stack Overflow! Strings are definitely a challenging part of Rust for many people, so there are a lot of questions about issues like this. You might find it useful to read [What are the differences between Rust's `String` and `str`?](https://stackoverflow.com/questions/24158114/what-are-the-differences-between-rusts-string-and-str) – trent Apr 08 '21 at 18:54

1 Answers1

2

You need to use "a".to_string().

fn letters() -> Vec<String> {
    let mut v = Vec::new();
    v.push("a".to_string());
    v.push("b".to_string());
    v
}
fn main() {
    println!("{:?}", letters());
}
Unapiedra
  • 15,037
  • 12
  • 64
  • 93