Use type itself as typeparameter

Is there any way to use "Self" as part of a type parameter?
E.g. pass Box<MyGenericStruct> to this type

struct MyGenericStruct<T> {
    f1: u32,
    f2: Option<T>
}

So that it becomes something like this:

struct MyStruct {
    f1: u32,
    f2: Option<Box<Self>>
}

Do I understand it correctly, that you want "MyStruct" to hold an instance of "MyStruct"?

If yes, take a look at the Rust book:
https://doc.rust-lang.org/stable/book/ch15-01-box.html
https://doc.rust-lang.org/stable/book/ch15-04-rc.html

sorry, something got lost when pasting the examples ... here are the right ones...
E.g. pass Box to this type

struct MyGenericStruct<T> {
f1: u32,
f2: Option<T>
}

So that it becomes something like this:

struct MyGenericStruct {
f1: u32,
f2: Option<Box<MyGenericStruct>>
}

However so that I could also (for example) pass in an u64:

struct MyGenericStruct {
f1: u32,
f2: Option<u64>
}

The reason I want this, is that I want to have two variants of MyGenericStruct - one that might contain loops through self references (be it Box, Rc, ARC, or plain references) and one that just stores an index to the otherwise referenced instance to avioid loops for serialization.

Box<MyGenericStruct> is not Self. There's nothing to automatically tell the typesystem when to insert Box.

This is closest I could come up with:

struct BoxedGenericStruct(Box<MyGenericStruct<BoxedGenericStruct>>);

struct MyGenericStruct<T> {
  f1: u32,
  f2: Option<T>
}

fn main() {
    let x: MyGenericStruct<BoxedGenericStruct>;
}

BTW, please surround code blocks with ```

thanks, this worked.

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