Ownership and Moves
Lesson 16 of 48 in Coddy's Rust for Java Developers course.
Java assignment of an object reference creates another reference to the same object. The garbage collector tracks reachability; assigning or passing that reference does not invalidate the original variable. Rust owned values follow a different rule. Assigning a String transfers ownership unless you explicitly clone it. The moved-from binding cannot then be used as though it still owned the string.
A move does not imply copying the heap buffer or immediately destroying it. Responsibility for the value moves to the destination, and its owned resources are normally released when the owner is dropped. clone() creates a separate owned value according to that type's implementation. Java String is immutable, so a mutable StringBuilder makes aliasing visible in the source example. Rust String is owned UTF-8 text and can be mutated through a mutable owner. Rust Copy is available for suitable types such as integers, not for String.
Java: complete program
class Main {
public static void main(String[] args) {
StringBuilder first = new StringBuilder("reed");
StringBuilder second = first;
second.setCharAt(0, 's');
System.out.println(first + ":" + second);
}
}Rust: complete program
fn main() {
let first = String::from("reed");
let mut second = first.clone();
second.replace_range(0..1, "s");
let owner = second;
println!("{}:{}", first, owner);
}Pitfall: let second = first is not a second Java-style reference when first is an owned String.
Challenge
EasyImplement pub fn dispatch(mut label: String) -> (String, usize) in parcel.rs. It takes ownership of the label, records its original UTF-8 byte length, appends :sent, and returns the resulting owned string and original byte length. Empty labels are valid. Implement solve(input: &str) -> String: treat the entire input, including any spaces, as the label and return length|dispatched-label. Inputs contain no newlines. Use the API; the locked driver also calls it directly.
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, parcel.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 parcel;
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 owned = String::from("hold-é");
let backup = owned.clone();
assert_eq!(parcel::dispatch(owned), (String::from("hold-é:sent"), 7));
assert_eq!(backup, "hold-é");
assert_eq!(parcel::dispatch(String::new()), (String::from(":sent"), 0));
assert_eq!(parcel::dispatch(String::from(":sent")), (String::from(":sent:sent"), 5));
// 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 Java 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