Skip to content
TheChatArchiveThe Chat Archive
Coherecommand-a-03-2025· CohereHugging Face LMArena Human Preference 140K

How do I create a shared pointer in Rust?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-sonnet-20241022’s answer.
  1. User

    How do I create a shared pointer in Rust?

  2. Cohere Assistant

    Rust does not have a direct equivalent to C++'s shared_ptr because Rust's ownership model is fundamentally different. Instead of shared ownership with reference counting, Rust uses smart pointers like Rc (Reference Counted) and Arc (Atomic Reference Counted) to achieve similar functionality.

    Here’s how you can create and use shared ownership in Rust:

    1. Rc<T> (Reference Counted)

    Use Rc<T> for single-threaded shared ownership.

    use std::rc::Rc;
    
    fn main() {
        let data = Rc::new(String::from("Hello, Rc!"));
    
        let clone1 = Rc::clone(&data); // Increment reference count
        let clone2 = Rc::clone(&data); // Increment reference count
    
        println!("Data: {}", data);
        println!("Clone1: {}", clone1);
        println!("Clone2: {}", clone2);
    
        // When all clones go out of scope, the data is dropped
    }
    

    2. Arc<T> (Atomic Reference Counted)

    Use Arc<T> for multi-threaded shared ownership.

    use std::sync::Arc;
    use std::thread;
    
    fn main() {
        let data = Arc::new(String::from("Hello, Arc!"));
    
        let clone1 = Arc::clone(&data);
        let clone2 = Arc::clone(&data);
    
        let handle1 = thread::spawn(move || {
            println!("Thread 1: {}", clone1);
        });
    
        let handle2 = thread::spawn(move || {
            println!("Thread 2: {}", clone2);
        });
    
        handle1.join().unwrap();
        handle2.join().unwrap();
    
        // The original `data` is still accessible here
        println!("Main: {}", data);
    }
    

    Key Differences from C++ shared_ptr:

    • No Cyclic References: Rust's Rc and Arc do not support cyclic references, as they can lead to memory leaks. For cyclic references, use Weak<T> (for Rc) or WeakArc<T> (not directly available, but can be implemented).
    • Thread Safety: Rc is for single-threaded use, while Arc is for multi-threaded use.
    • Ownership Model: Rust's smart pointers are part of its ownership system, ensuring memory safety at compile time.

    Using Weak<T> to Avoid Cyclic References

    If you need to break cyclic references, use Weak<T> with Rc or implement a similar pattern with Arc.

    use std::rc::{Rc, Weak};
    
    #[derive(Debug)]
    struct Node {
        value: i32,
        parent: Option<Weak<Node>>,
    }
    
    fn main() {
        let apple = Rc::new(Node { value: 1, parent: None });
        let banana = Rc::new(Node {
            value: 2,
            parent: Some(Rc::downgrade(&apple)),
        });
    
        println!("Apple: {:?}", apple);
        println!("Banana: {:?}", banana);
    }
    

    In summary, Rust's Rc<T> and Arc<T> provide shared ownership semantics similar to C++'s shared_ptr, but with Rust's unique memory safety guarantees.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.