rust-bakery/nom

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

ChaoticWyrme opened this issue · 2 comments

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

  • Rust version : rustc 1.70.0 (90c541806 2023-05-31)
  • nom version : 7.1.3
  • nom compilation features used: std

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

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.