Shall there be a trait for creating smart pointers in std?

Rc and Arc both have “new” method outside any trait. Many other smart pointers can probably also have this trait.

trait SmartPointer<T> { fn new(t : T) -> Self; }

Is it a good idea? How this trait should be named?

Have you seen the box-RFC? It doesn’t work for generics. But at least you can do the following:

let x: Rc<i32> = box 5;

What you want is actually: trait SmartPointer<T> { fn new(t : T) -> Self<T>; } Because Self has kind * -> *, such trait cannot be declared in current Rust.

Not sure I understand what you mean. It works just as @vi0 suggests. PlayPen

use std::rc::Rc;

trait SmartPointer<T> { fn new(t : T) -> Self; }

impl<T> SmartPointer<T> for Box<T> {
    fn new(t: T) -> Box<T> {
        Box::new(t)
    }
}

impl<T> SmartPointer<T> for Rc<T> {
    fn new(t: T) -> Rc<T> {
        Rc::new(t)
    }
}

fn main() {
    let x = SmartPointer::new(42);
    let y : Rc<i32> = x;
}

@ker the problem is that this trait is not particularly useful, because if I want to be generic over Rc and Arc, it’s usually using internal implementation details. So e.g. I want to be generic over Rc<SecretNodeType> and Arc<SecretNodeType>, and there’s no way for a user of my interface to feed in Smaht<SecretNodeType> short of me making it public (and that’s awful(. What I want is to accept a Smaht<*>, that I can monomorphize with undeclared, and indeed multiple types. This is Higher Kinded Types, which is unlikely to happen for a long while.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.