Tomok
February 1, 2020, 8:14am
1
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
Tomok
February 1, 2020, 8:30am
3
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.
kornel
February 1, 2020, 1:16pm
4
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 ```
system
Closed
May 1, 2020, 4:56pm
6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.