相关疑难解决方法(0)

如何在Rust中匹配字符串与字符串文字?

我正在试图弄清楚如何匹配StringRust.

我最初尝试过像这样的匹配,但我发现Rust不能暗中强制转换std::string::String&str.

fn main() {
    let stringthing = String::from("c");
    match stringthing {
        "a" => println!("0"),
        "b" => println!("1"),
        "c" => println!("2"),
    }
}
Run Code Online (Sandbox Code Playgroud)

这有错误:

error[E0308]: mismatched types
 --> src/main.rs:4:9
  |
4 |         "a" => println!("0"),
  |         ^^^ expected struct `std::string::String`, found reference
  |
  = note: expected type `std::string::String`
             found type `&'static str`
Run Code Online (Sandbox Code Playgroud)

然后我尝试构造新String对象,因为我找不到将a String转换为a的函数&str.

fn main() {
    let stringthing = String::from("c");
    match stringthing {
        String::from("a") => println!("0"),
        String::from("b") => …
Run Code Online (Sandbox Code Playgroud)

string match rust

153
推荐指数
4
解决办法
5万
查看次数

笛卡尔积匹配

我有两组不完整的类型(即结构名称、缺少泛型参数和生命周期),我需要为每个可能的组合执行一些代码:

// these are my types
struct A<T> { ... }
struct B<'a, 'b, T> { ... }
struct C { ... }

struct X<T> { ... }
struct Y { ... }
struct W<'a> { ... }
struct Z<T, D> { ... }

// this is the code I need to generate
match (first_key, second_key) {
    ("a", "x") => { ... A ... X ... }
    ("a", "y") => { ... A ... Y ... }
    ("a", …
Run Code Online (Sandbox Code Playgroud)

macros nested match repeat rust

5
推荐指数
1
解决办法
334
查看次数

标签 统计

match ×2

rust ×2

macros ×1

nested ×1

repeat ×1

string ×1