Rust split_at
Created By: chatGPT
split_at is a method in Rust that allows you to divide a slice into two non-overlapping parts. This is particularly useful for working with collections when you want to partition data based on an index. The split_at method returns a tuple containing two slices: the first slice contains elements from the start up to the specified index, and the second slice contains the remaining elements. It's important to ensure that the index you provide is within the bounds of the slice to prevent panic during runtime.
fn main() {
let arr = [1, 2, 3, 4, 5];
let index = 2;
let (first, second) = arr.split_at(index);
println!("First part: {:?}", first);
println!("Second part: {:?}", second);
}
In this example, the
arr
array is split into two parts at index 2. The first slice will contain the elements [1, 2]
and the second will contain [3, 4, 5]
. This illustrates how you can use split_at to access and manipulate different sections of your data efficiently.fn main() {
let name = "Rust Programming";
let index = 4;
let (first_part, second_part) = name.split_at(index);
println!("First part: {}", first_part);
println!("Second part: {}", second_part);
}
Here’s another example with a string slice. When splitting the string at index 4, it effectively separates the word into two segments:
"Rust"
and " Programming"
. This demonstrates the versatility of split_at for both arrays and strings.fn main() {
let slice = [10, 20, 30, 40, 50];
let index = 3;
let (left, right) = slice.split_at(index);
let sum_left: i32 = left.iter().sum();
let sum_right: i32 = right.iter().sum();
println!("Sum of left part: {}", sum_left);
println!("Sum of right part: {}", sum_right);
}