Home
Rust
Range Type Examples
Updated Jan 30, 2025
Dot Net Perls
Range. 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.
Generic
struct
usize
Example. 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.
Part 1 The Example struct has a field of type Range(usize) and this means the Range has a start and end with usize values.
Part 2 We create an instance of the Example struct, specifying the start and end based on same-named local variables.
Part 3 We can use a shortened syntax to create a Range: we use 2 periods in between the start and end values.
Part 4 A range (even a local Range variable) can be used index an array or other slice and get a slice.
Part 5 For convenience, the Range struct provides a contains() function, and this can be used to see if a value falls within a range.
contains
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!
Summary. 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).
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 30, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen