I am trying to convert an integer to byte literal in Rust:
for x in 0..10000 {
let key = x.to_???;
other_function(key);
}
Could not find it in the docs.
I am trying to convert an integer to byte literal in Rust:
for x in 0..10000 {
let key = x.to_???;
other_function(key);
}
Could not find it in the docs.
A byte literal
is something like b'f'
, a literal value written down. You probably mean a byte
, which is usually a u8
, sometimes an i8
. You can use the TryFrom
-trait on recent rust:
use std::convert::TryFrom;
fn main() {
for i in 253..257 {
let u = u8::try_from(i).expect("Not all integers can be represented via u8");
println!("{}", u);
}
}
u
inside the loop is an u8
. The code will print 253, 254, 255 and crash on the iteration where i
becomes larger than what a u8
can represent.