rust-bakery / nom

Rust parser combinator framework
MIT License
9.38k stars 805 forks source link

Number literal defaults to i32, failing to satisfy the ToUsize trait #1674

Open ChaoticWyrme opened 1 year ago

ChaoticWyrme commented 1 year ago

When you use a literal as the argument to take, it assumes it is an i32 by default, and has a compilation error, since i32s cannot be turned into usize. The workaround is to create a variable with an explicit u* type, and pass it in.

Prerequisites

Test case

use nom::bytes::complete::take;

fn main() {
    let data = [1, 2, 3, 4, 5];
    println!("{:?}", take(1)(data.as_slice()).unwrap());
}

On the rust playground

error[[E0277]](https://doc.rust-lang.org/stable/error_codes/E0277.html): the trait bound `i32: ToUsize` is not satisfied
   --> src/main.rs:5:27
    |
5   |     println!("{:?}", take(1)(data.as_slice()).unwrap());
    |                      ---- ^ the trait `ToUsize` is not implemented for `i32`
    |                      |
    |                      required by a bound introduced by this call
Xiretza commented 1 year ago

A slightly less awkward workaround is to specify the type of the literal directly (i.e. 1_usize), but that's obviously still not ideal.