Arrays and Slices
Lesson 13 of 48 in Coddy's Rust for C Developers course.
A Rust array has a fixed length in its type: [i32; 4] holds four integers. [0; 4] creates four zeroes, while [2, 5, 8, 9] lists individual values. A C array parameter commonly decays to a pointer and needs a separate length argument. A Rust slice, written &[i32], borrows a contiguous sequence together with its length. &array[start..end] forms a slice with an exclusive end. Indexes use usize; .len() returns that type. Indexing is checked and panics outside the slice, unlike C undefined behavior. Check the length before indexing an optional element. &mut [i32] permits mutation through a temporary exclusive borrow; &[i32] permits reads. The example swaps two positions through a mutable subslice, showing that the view refers to the original array.
C
#include <stdio.h>
#include <stddef.h>
void swap_first_two(int *values, size_t count) {
if (count < 2) return;
int first = values[0]; values[0] = values[1]; values[1] = first;
}
int main(void) {
int data[4] = {2, 5, 8, 9};
swap_first_two(data + 1, 2);
printf("%d %d %d %d\n", data[0], data[1], data[2], data[3]);
return 0;
}Rust
fn swap_first_two(values: &mut [i32]) {
if values.len() < 2 { return; }
let first = values[0];
values[0] = values[1];
values[1] = first;
}
fn main() {
let mut data = [2, 5, 8, 9];
swap_first_two(&mut data[1..3]);
println!("{} {} {} {}", data[0], data[1], data[2], data[3]);
}A slice is not a copied array. Mutating through a mutable slice changes the corresponding elements of its owner.
Challenge
EasyInspect a sequence. Input is zero to twenty whitespace-separated integers between -1000 and 1000; empty input is valid. Required API: pub fn alternating(values: &[i32]) -> i32 adds the element at index zero, subtracts the element at index one, and continues alternating signs. pub fn ends(values: &[i32]) -> i32 adds the first and last elements, counting a single element only once; an empty slice returns zero. Neither API may modify the slice. Output alternating ends as two decimal integers separated by one space. The APIs must work for subslices as well as whole arrays or vectors. Implement the public API in sequence.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, sequence.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod sequence;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let data = [90, 7, -3, 11, 2, 80];
assert_eq!(sequence::alternating(&data[1..5]), 19);
assert_eq!(sequence::ends(&data[1..5]), 9);
assert_eq!(sequence::alternating(&[]), 0);
assert_eq!(sequence::ends(&[]), 0);
assert_eq!(sequence::alternating(&[-8]), -8);
assert_eq!(sequence::ends(&[-8]), -8);
assert_eq!(data, [90, 7, -3, 11, 2, 80]);
assert_eq!(sequence::alternating(&data[1..5]), 19);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler