0

I'm trying to implement a network card game and I need to parse a string and get the rank value as a u32. The string looks like this

let response: String = "(6, Hearts)".to_string();

I've tried using:

let rank = response.chars().nth(1).unwrap() as u32;

with this I get a rank of 54 instead of 6 I think because it's returning a byte index instead of the actual value. I've also tried this:

let rank: u32;
response.chars()
        .find(|x| 
            if x.is_digit(10) {
                rank = x.to_digit(10).unwrap();
            }
        );
println!("rank {}", rank);

For this one I'm getting a mismatch type error on the closure

   Compiling playground v0.0.1 (file:///playground)
error[E0308]: mismatched types
  --> src/main.rs:12:35
   |
12 |                   if x.is_digit(10) {
   |  ___________________________________^
13 | |                     rank = x.to_digit(10).unwrap();
14 | |                 }
   | |_________________^ expected bool, found ()
   |
   = note: expected type `bool`
              found type `()`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

Here's a link to the code: https://play.rust-lang.org/?gist=120b0ee308c335c9bc79713d3875a3b4&version=stable&mode=debug

2
  • let rank = response.chars().flat_map(|x| x.to_digit(10)).next().unwrap(); or let rank = response.chars().nth(1).unwrap() as u32 - '0' as u32; or let rank: u32 = response[1..][..1].parse().unwrap();, etc. Commented Jun 3, 2018 at 2:24
  • I'd encourage you to re-read The Rust Programming Language to refresh yourself on basic data types. In Rust, a single character and a string are related but distinct data types. Commented Jun 3, 2018 at 2:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.