Search code examples
rustvectorarguments

How to send a vector of strings to a function


I am trying to learn Rust. I am trying to send a vector of strings to a function. I am using following code:

fn myfn(svect: vec![String]) -> &'static str{
  "A string will be created from svect and returned."
}

However, I am getting following error:

error: expected type, found `<[_]>::into_vec(#[rustc_box] ::alloc::boxed::Box::new([String]))`
   --> src/main.rs:196:16
    |
196 | fn myfn(svect: vec![String]) -> &'static str{
    |                ^^^^^^^^^^^^
    |                |
    |                expected type
    |                in this macro invocation
    |                this macro call doesn't expand to a type
    |
    = note: this error originates in the macro 
`$crate::__rust_force_expr` which comes from 
the expansion of the macro `vec` (in Nightly 
builds, run with -Z macro-backtrace for more info)

I tried using Vec, Vec!, String::String but all give errors.

Where is the problem and how can it be solved?


Solution

  • You can do something like this:

    fn process_strings(strings: Vec<String>) 
    {
        //Do something
    }
    
    fn main() 
    {
        let strings = vec!["Hello".to_string(), "world".to_string(), "!".to_string()];
        process_strings(strings);
    }
    

    You can also use slices:

    fn process_strings(strings: &[&str]) 
    {
        //Do something
    }
    
    fn main() 
    {
        let strings = vec!["Hello", "world", "!"];
        let string_slices: Vec<&str> = strings.iter().map(|s| s.as_str()).collect();
        process_strings(&string_slices);
    }