HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How to match a String against string literals?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howagainststringmatchliterals

Problem

I'm trying to figure out how to match a String in Rust.

I initially tried matching like this, but I figured out Rust cannot implicitly cast from std::string::String to &str.

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


This has the error:

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


I then tried to construct new String objects, as I could not find a function to cast a String to a &str.

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


This gave me the following error 3 times:

error[E0164]: String::from does not name a tuple variant or a tuple struct
--> src/main.rs:4:9
|
4 | String::from("a") => return 0,
| ^^^^^^^^^^^^^^^^^ not a tuple variant or struct


How to actually match Strings in Rust?

Solution

You can do something like this:

match &stringthing[..] {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}


There's also an as_str method as of Rust 1.7.0:

match stringthing.as_str() {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}

Code Snippets

match &stringthing[..] {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}
match stringthing.as_str() {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}

Context

Stack Overflow Q#25383488, score: 198

Revisions (0)

No revisions yet.