Using to_digit() gives "not in scope" error

I'm continuing my quest to learn Rust. Currently, I'm working on a simple app that will sum the digits of a multiple-digit integer. Should be simple enough if I can use the to_digit() method. Here's my code so far:

fn main() {
let intchar = "4";
println!("\nThe character is: {intchar}",);
let asint = to_digit(intchar, 10);
println("\nThe digit is {asint}");
println("\nThe digit plus 2 is {}", asint + 2);
}

My problem is that the compiler tells me that to_digit() isn't in scope. I tried use::char; and use::char::to_digit; but those just created more errors.

Note: I used

as my source to read up on how to_digit() works.

Can someone set me straight? Thanks.

  • to_digit is a method, not a function. You use it like intchar.to_digit(10).

  • The syntax for bringing something into scope is use std::char (there's a space after use).

  • char literals use single quotes, so it should be '4', not "4".

1 Like

Well, once again I'm wondering why I didn't catch that myself. Thanks, @kornel. I fixed it and those errors disappeared, but I can't get any output. Apparently the to_digit() method returns an Option<u32> type and the ```println!()`` function doesn't like it. So, stuck again. Here's my code so far (returning errors telling me that it doesn't like the Option type):

    let intchar = '4';
    println!("\nThe character is:     {intchar}",);
    let asint = intchar.to_digit(10);
    println!("\nThe digit is {}", asint);
    println!("\nThe digit plus 2 is {}", asint + 2);
}```

Anyone care to "unstick" me?  Thanks.

The to_digit() method returns an Option, because the char might not be a digit, so you should check if the value is present, or check for None in case it's not a digit what's inside the char.

Also, beware that your approach will only work for single-digit strings. A more robust solution would be to parse the string to an int, something like:

let s = "1240";

let s_int = s.parse::<i32>().unwrap();
// or
let s_int: i32 = s.parse().unwrap();
1 Like

Thanks for your input. My first attempt at solving this little problem actually did parse a string obtained from read_line() that had already been checked to ensure that it really was an integer. The issue is that I need to add the individual digits. My solution (undoubtedly clumsy) was/is to convert that inputted integer back into a string, convert that string into a character vector, and then use to_digit() to convert each element of the vector into a single-digit integer that I can then use to find the sum of the digits of the integer. This little snippet of code is my attempt at learning how to use to_digit(). So, since I've already checked for non-numerical input and handled any input errors, how do I pull the digit's value out of to_digit() so that I can use it either as output or to combine it with other values?

you can use the unwrap() method.

fn main() {
let intchar = '4';
println!("\nThe character is: {intchar}",);
let asint = intchar.to_digit(10);
println!("\nThe digit is {}", asint.unwrap());
println!("\nThe digit plus 2 is {}", asint.unwrap() + 2);
}
1 Like

Your post looks like my first post :grinning:

You can place rust code between ``` and ``` for nice looking:

fn main() {
   let intchar = "4";
   println!("\nThe character is: {intchar}",);
   let asint = to_digit(intchar, 10);
   println("\nThe digit is {asint}");
   println("\nThe digit plus 2 is {}", asint + 2);
}

And instead of:

let intchar = "4";

try to use full syntax:

let intchar:char = "4";

In this case rust compiler will say '4' is better than "4".

Thanks, everyone. I got it working and learned a bunch in the process.

2 Likes

In the end I left to_digit() behind and used this code:

dig = chr_vec[i] as u32 - 0x30;

Using "as" returns the ASCII code for the digit in question and the - 0x30 adjusts that number to match up with the digit. It worked, though I don't know that relying on the ASCII number to convert to a digit is the best way to solve the problem.

So, this morning, I went back and, as you suggested, inserted unwrap() into my code and it worked very nicely. Thanks for the advice.

To follow up some more, I found this code on a different forum:

    const RADIX: u32 = 10;
    let x = "134";
    println!("{}", x.chars().map(|c| c.to_digit(RADIX).unwrap()).sum::<u32>());
}```

I find the ```println!``` line of that code utterly confusing.  I'd love it if someone could ```unwrap()``` it for me.  :>)

@rustart Thanks for the pointer, but it doesn't seem to be working for me. Take a look at my recent reply to @samuvlad. It cut the top line off the code I pasted and then included the rest of my post in the special formatting. What am I doing wrong?

Put the last ``` on a line by itself to get code formatting to work properly.

Welcome to the world of Rust. :smiley:

I don't know if anyone has directed you to The Book but you really need to read it. Trying to learn Rust by trial and error will work for a while, but eventually you will hit a wall. Rust differs from most other languages in enough ways that without in-depth information on how it works you will experience unnecessary difficulty and frustration.

x.chars() return Chars(['1', '3', '4'])

the map function takes each previous value separately (1, 3, 4) and applies the to_digit (RANDIX) function to it.
RANDIX = 10 means that it is in base 10, that is, in decimal base

the funtion to_digit(RANDIX) returns un option struct, so tou need tp use unwrap()

finally the function sum() adds the three values โ€‹โ€‹of type u32

sorry for my english, it's really bad :slight_smile:

1 Like

Thanks for the advice. I've been working my way through the Rust book along with another rust programming book I have on my Kindle app. I'm also working my way through a Udemy course on learning Rust. Those are all good resources and the forum is really helping clarify questions that I haven't yet found the answers for.

@samuvlad Thanks! That does help me understand that line better.

So, I'm assuming that English is a second language (ESL) for you. Your English isn't as bad as you think. I'm a retired school teacher and have seen much worse. Really, you put your words together just fine. Use capitals at the beginning of your sentences and periods to end them and no one would guess you are ESL.

2 Likes