简体   繁体   English

类型不匹配:在分配字符串时预期&str找到了字符串

[英]Mismatched types: expected &str found String when assigning string

I'm trying to assign variable value (type String ) based on the number of args: 我正在尝试根据args的数量分配变量值(类型String ):

let mut out_filename = "";
let args: Vec<_> = env::args().collect();
match args.len() {
    2 => out_filename = args[1],
    3 => out_filename = args[2],
    _ => panic!("To many params !"),
};

And I'm getting 我正在

src/main.rs:39:29: 39:36 error: mismatched types:
 expected `&str`,
    found `collections::string::String`
(expected &-ptr,
    found struct `collections::string::String`) [E0308]
src/main.rs:39         2 => out_filename = args[1],

How to make a match statement where the match value (1,2,3) is just a selector and the returned type is different? 如何在匹配值(1,2,3)只是选择器而返回的类型不同的情况下做出match语句? There is no let var = match .. 没有let var = match ..

You initialized out_filename with a string literal. 您使用字符串文字初始化了out_filename The type of a string literal is &str (or, more specifically, &'static str ), which is different from String . 字符串文字的类型为&str (或更具体地说,为&'static str ),它与String不同。

The simplest solution is to assign out_filename to the result of the match expression directly: 最简单的解决方案是直接将out_filename分配给match表达式的结果:

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let out_filename = match args.len() {
        2 => &args[1],
        3 => &args[2],
        _ => panic!("Too many params !"),
    };
}

[...] what if I wanted to make group of assignments based on args count like inside code block {} ? [...]如果我想基于args计数(如内部代码块{})进行赋值,该怎么办? [...] Is there any way to get working code with basic match without let var = match { assign ? [...]没有let var = match {分配?

You can simply put some let statements with no initializers before the match expression and initialize the variables as appropriate in each arm. 您可以简单地将一些没有初始化程序的let语句放在match表达式之前,并在每个分支中适当地初始化变量。 You'll get a compiler error if you try to use a variable that might be left undefined and, unless you define the variables with let mut , you'll also get an error if you try to assign a variable more than once on a particular code path. 如果尝试使用可能未定义的变量,则会出现编译器错误;除非使用let mut定义变量,否则如果尝试在一个特定的变量上多次分配变量,也会遇到错误代码路径。

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let out_filename;
    match args.len() {
        2 => out_filename = &args[1],
        3 => out_filename = &args[2],
        _ => panic!("Too many params !"),
    };
}

As Francis Gagné mentioned, String and &str are not the same. 正如弗朗西斯·加涅(FrancisGagné)所提到的, String&str是不同的。 The easiest way to convert them is to just use to_string() . 转换它们的最简单方法是只使用to_string() It isn't always the best thing to do, but it will do while you are just learning because it will mostly work. 并非总是最好的事情,但它会在您刚学习时就起作用,因为它通常会起作用。 You can read more about strings here . 您可以在此处阅读有关字符串的更多信息

let mut out_filename = "".to_string();
let args: Vec<_> = env::args().collect();
match args.len() {
    2 => out_filename = args[1].clone(),
    3 => out_filename = args[2].clone(),
    _ => panic!("To many params !"),
};

Note, I also fixed another error you would have come across, because of moving a value out of args . 注意,由于将值移出了args ,我还解决了另一个错误。 Explicitly cloning them, as I have done above, is one way of fixing that, and probably the easiest because you won't have to worry about lifetimes either. 像我上面所做的那样,明确克隆它们是解决此问题的一种方法,并且可能是最简单的方法,因为您也不必担心生命周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM