Programming

Rust에서 문자열 리터럴과 문자열을 일치시키는 방법은 무엇입니까?

procodes 2020. 6. 19. 22:09
반응형

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"),
    }
}

이것은 오류가 있습니다 :

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`

그런 다음에을 String캐스팅하는 함수를 찾을 수 없으므로 객체 를 만들려고 String했습니다 &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"),
    }
}

이로 인해 다음과 같은 오류가 세 번 발생했습니다.

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

StringRust에서 s 를 실제로 일치시키는 방법은 무엇입니까?


as_slice더 이상 사용되지 않습니다. 이제 특성을 std::convert::AsRef대신 사용해야합니다 .

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

포괄 사건을 명시 적으로 처리해야합니다.


다음과 같이 할 수 있습니다 :

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

as_strRust 1.7.0부터 방법 이 있습니다 .

match stringthing.as_str() {
    "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!"),
}

보다:


Editor's note: This answer pertains to an version of Rust before 1.0 and does not work in Rust 1.0

You can match on a string slice.

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

참고URL : https://stackoverflow.com/questions/25383488/how-to-match-a-string-against-string-literals-in-rust

반응형