Search code examples
rust

Can I use deref as part of a method chain?


Is there some way to use the deref operator * as part of a method chain?

For example:

let replacement_numbers = HashMap::from([
    ("one", "1"),
    ("two", "2"),
    ("three", "3"),
]);

let number: &str = "one";
let default_number: &str = "0";

let replacement = replacement_numbers // <-- HashMap<&str, &str>
    .get(number)  // <-- Option<&&str>
    .unwrap_or(&default_number)  // <-- &&str
    .to_digit(10) // <-- does not work on &&str, only &str!
    .expect("Should be a number!");

I need to somehow dereference that &&str into a &str before I can call to_digit(10) on it. Is it possible to do that in a method call? I tried using .deref() but that does not work.


Solution

  • Your code would work just fine if str defined to_digit, as Rust will dereference repeatedly to find a method. Problem is, to_digit is a method on char, not str.

    For &str (or &&str, or &&&str, etc.), you could use .parse() (possibly annotating replacement or using turbofish to specify the type), or use the from_str_radix functions of the various primitive types, e.g. u32::from_str_radix.