Menu
CoddyTech

Arrays and Slices

Lesson 13 of 48 in Coddy's Rust for Java Developers course.

Java arrays are heap objects with a fixed length, and assigning an array variable copies a reference. Rust [T; N] stores exactly N elements and includes that length in its type. A Rust slice [T] has a length known at runtime; a shared slice reference &[T] borrows a contiguous region. A function that accepts a slice can work with portions of either arrays or vectors.

Rust indexing checks bounds and can panic; get offers a checked lookup returning Option. Taking &array[start..end] borrows a region without copying it. Java Arrays.copyOfRange creates a new array instead, so the storage relationship differs even when printed values match. Both examples select the middle pair, but only the Rust view depends on the original storage remaining alive.

Java: complete program

class Main {
    public static void main(String[] args) {
        int[] a = {8, 3, 5, 9};
        int[] middle = java.util.Arrays.copyOfRange(a, 1, 3);
        a[1] = 7;
        System.out.println(middle[0] + ":" + middle.length);
    }
}

Rust: complete program

fn main() {
    let mut a = [8, 3, 5, 9];
    a[1] = 7;
    let middle = &a[1..3];
    println!("{}:{}", middle[0], middle.len());
}

Pitfall: a Rust slice is not a new array and cannot outlive the storage it borrows.

challenge icon

Challenge

Easy

Inspect 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler