-
Notifications
You must be signed in to change notification settings - Fork 12.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Creating an unsized struct #18806
Comments
|
Hum, ok. Returning So let’s look at returning pub struct Foo {
header: u16,
bytes: [u8]
}
impl Foo {
fn new(bytes: Box<[u8]>) -> Box<Foo> {
box Foo { header: 4, bytes: *bytes }
}
} |
You need to use generics and coercions (using struct Foo<Sized? T> {
foo: T
}
fn main() {
let foo_sized: Foo<[uint, .. 4]> = Foo { foo: [1u,2,3,4] };
let foo_unsized: &Foo<[uint]> = &foo_sized;
for &i in foo_unsized.foo.iter() {
println!("{}", i);
}
} |
@SimonSapin According to my understanding:
Since But I could be wrong. You should ask @nick29581 |
@bkoropoff's suggestion is correct, the preferred way to create an unsized struct is via coercion. You won't be able to do |
To make something actionable here, we should probably have a 'raw' struct (something like I don't see a way to allow creating such structs in a generic, safe way and I'm not sure it is something we should encourage. If there is a use case for this, then it would have to implemented as a language feature and would be post-1.0. If there is a strong use case, please file an issue on the RFCs repo. |
Closing as I don’t think there is much actionable here. I opened this based on a “there has to be a better way” feeling, but understand that it pretty much has to be transmute or coercion since we can’t have generics over the set of fields in a struct. |
If you happen upon this issue, there is some forward progress on e.g. rust-lang/rfcs#1808, rust-lang/rfcs#1909 |
There is apparently no way to construct unsized struct. This can be worked around with
transmute
, but only if the struct only has one field (the unsized one). Even with a single field, there should be a way to do this withoutunsafe
.Test case:
Output:
A work-around:
The text was updated successfully, but these errors were encountered: