It is possible to create custom structs in Rust that store start and end indexes, but the Range struct
can do this in a more standard way. We can use Range from std ops.
A generic type, Range can represent its start and end with a numeric type like usize
. It is possible to use special, shortened syntax to create a Range.
This program uses the Range struct
within a struct
, and as a local variable in the main function. We can get a slice from an array with a Range.
struct
has a field of type Range(usize
) and this means the Range has a start and end with usize
values.struct
, specifying the start and end based on same-named local variables.struct
provides a contains()
function, and this can be used to see if a value falls within a range.use std::ops::Range; // Part 1: use Range as a field in a struct. struct Example { range: Range<usize>, } fn main() { // Part 2: create struct containing range with 2 integers. let start = 10; let end = 20; let example = Example { range: Range { start, end }, }; println!("{:?}", example.range); // Part 3: create struct containing range with simpler syntax. let example2 = Example { range: start..end }; println!("{:?}", example2.range); // Part 4: use inclusive range, and print values from array directly with named range. let bytes = [100, 101, 102, 103, 104]; let range = 2..=4; println!( "{:?} {:?} {:?}", range.clone(), &bytes[range], &bytes[2..=4] ); // Part 5: see if range contains an integer. let range2 = 5..15; if range2.contains(&10) { println!("Range contains 10!"); } }10..20 10..20 2..=4 [102, 103, 104] [102, 103, 104] Range contains 10!
Ranges are used frequently in Rust programs, and every time we use the short
range syntax to get a slice, we are creating a range. Range is found in the standard library (std ops).