Skip to content

Creating an unsized struct #18806

Closed
Closed
@SimonSapin

Description

@SimonSapin

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 without unsafe.

Test case:

pub struct Foo {
    bytes: [u8]
}

impl Foo {
    fn new(bytes: &[u8]) -> &Foo {
        &Foo { bytes: *bytes }
    }
}

Output:

a.rs:7:10: 7:31 error: the trait `core::kinds::Sized` is not implemented for the type `Foo`
a.rs:7         &Foo { bytes: *bytes }
                ^~~~~~~~~~~~~~~~~~~~~
a.rs:7:10: 7:31 note: structs must have a statically known size to be initialized
a.rs:7         &Foo { bytes: *bytes }
                ^~~~~~~~~~~~~~~~~~~~~

A work-around:

    fn new(bytes: &[u8]) -> &Foo {
        unsafe { ::std::mem::transmute(bytes) }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions