Share String Data With Rc<str>

Store one string as Rc<str> and hand out cheap pointer clones to many structs, with strong_count confirming the single shared allocation.

RustData Integrity

Code

rustsnippet
17 lines
use std::rc::Rc;

struct Route {
    path: Rc<str>,
}

fn main() {
    // Rc::from(&str):把字符串切片装进一份共享的堆缓冲
    let base: Rc<str> = Rc::from("/api/v1");

    let read = Route { path: Rc::clone(&base) };
    let write = Route { path: Rc::clone(&base) };

    // 三个所有者指向同一份数据:clone 只复制指针,不复制内容
    println!("strong count: {}", Rc::strong_count(&base));
    println!("{} {} {}", base, read.path, write.path);
}

One allocation, three owners

Rc::from(“/api/v1”) puts the string into a single shared heap buffer. Two Route structs take Rc::clone(&base), which copies only the pointer; strong_count prints 3 for base plus the two clones.

Why Rc and not String

Each String clone would duplicate the bytes; Rc shares one immutable buffer, so route-heavy structures pay pointer cost instead of byte cost.

Single-thread only

Rc is non-atomic; sharing across threads needs Arc. The demo stays single-threaded by construction and prints the three paths from one buffer.

Interactive Tools for This Topic

FAQ

Why does Rc::clone print a strong count of 3?
The count tracks owners of the single allocation: base plus the two Route clones — the bytes themselves were never duplicated.
Why is Rc<str> cheaper than cloning Strings?
String clones copy the full byte content; Rc<str> hands out pointer bumps over one shared immutable buffer.