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

zedzorander
  • 47
  • 1
  • 8
  • `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. – Shepmaster Jun 03 '18 at 02:24
  • I'd encourage you to re-read [*The Rust Programming Language*](https://doc.rust-lang.org/book/second-edition/ch03-02-data-types.html) to refresh yourself on basic data types. In Rust, a single character and a string are related but distinct data types. – Shepmaster Jun 03 '18 at 02:35

0 Answers0