This code compiles without problem:
fn main() {
let args: Vec<String> = env::args().collect();
let config = parse_config(&args);
}
struct Config {
query: String,
filename: String,
}
fn parse_config(args: &[String]) -> Config {
let query = args[1].clone();// why cannot I use &args[1].clone()
let filename = args[2].clone();// why cannot I use &args[2].clone()
Config {query, filename}
}
but if I change the two lines with comments in parse_confi()
into:
let query = &args[1].clone();
let filename = &args[2].clone();
I will get compile error:
error[E0308]: mismatched types
--> src/main.rs:35:13
|
35 | Config {query, filename}
| ^^^^^ expected struct `String`, found `&String`
|
help: try using a conversion method
|
35 | Config {query: query.to_string(), filename}
| ++++++ ++++++++++++
error[E0308]: mismatched types
--> src/main.rs:35:20
|
35 | Config {query, filename}
| ^^^^^^^^ expected struct `String`, found `&String`
|
help: try using a conversion method
|
35 | Config {query, filename: filename.to_string()}
| +++++++++ ++++++++++++
I just don't understand why I cannot add that reference there. args is a borrow, I just keep borrowing it. And how could String
be different from &String
?
I have encountered this similar problem many times, every time, I just easily follow the instruction of compiler and correct them. But I really don't understand why I cannot do that!
Thanks.