Menu
CoddyTech

Ownership and Moves

Lesson 16 of 48 in Coddy's Rust for C Developers course.

C assignment copies a pointer, so two pointer variables may refer to one allocation; deciding which one frees it is your responsibility. Rust String owns an allocation. Assigning it to another binding moves ownership and makes the old binding unusable. clone() makes an independent owned copy; it is explicit because it may allocate. Integers implement Copy, so assigning an integer leaves both bindings usable. Leaving scope drops owned values automatically; drop(value) can release one earlier and consumes it. A function taking String also receives ownership. Return the value when the caller should regain it. None of this needs raw pointers or unsafe.

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
    char *first = malloc(5);
    if (!first) return 1;
    strcpy(first, "note");
    char *copy = malloc(5);
    if (!copy) { free(first); return 1; }
    strcpy(copy, first);
    char *owner = first;
    first = NULL;
    owner[0] = 'N';
    int a = 3, b = a;
    printf("%s %s %d %d\n", owner, copy, a, b);
    free(owner);
    free(copy);
    return 0;
}

Rust

fn main() {
    let first = String::from("note");
    let copy = first.clone();
    let mut owner = first;
    owner.replace_range(0..1, "N");
    let a = 3;
    let b = a;
    println!("{} {} {} {}", owner, copy, a, b);
    drop(owner);
}

Do not translate an owning C pointer alias into two usable Rust String bindings. Use a borrow to share access or clone() when you need independent storage.

challenge icon

Challenge

Easy

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

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

All lessons in Rust for C Developers

Practice on your own: Online Rust compiler