Why does str.parse() return reference?

I'm dealing with strings of form "1234XX" (always 4 numeral, 2 non-numerals) and want to extract the number, interpreting as tenths. My example should map to a value of 123.4 thus.
This is what I came up with, and it works:

// value in first 4 characters
let value = match &datagram[..4].parse::<u16>() {
    Ok(val) => f64::from(*val) / 10.0,
    Err(_) => 0.0,
};

I think the code is beautiful in comparison with its C predecessor, but what really bugs me: I explicitly call the parse::<u16> variant, but in the Ok(val) match, val is a reference (&u16) rather than a u16.

Am I handling this correctly/idiomatically?

Prefix unary operators have lower precedence than methods and indexing. What you wrote is equivalent to

match &(datagram[..4].parse::<u16>())

Just remove the borrow.

1 Like

Oh well, it was me the whole time :tipping_hand_woman:
I had done something to a borrowed str slice &datagram[x..y] somewhere else and just stuck with it.
-- Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.