Structures with slices pointing to data on their own

I have a structure

struct Foo<'a> {
    buf: [u8, ..64],
    slice: &'a [u8]
}

The slice is supposed to indicate the bufstructure field . Is there any way to build such a structure? Sort of:

impl<'a> Foo<'a> {
    fn new() -> Foo<'a> {
        Foo {
            buf: [0, ..64],
            slice: ???? /* I don't know what to write here */
    }
}

If I try to do something like the following, the loan verification tool complains (correctly), as the slice will have a shorter life than the structure.

impl<'a> Foo<'a> {
    fn new() -> Foo<'a> {
        let buf = [0, ..64];
        Foo {
            buf: buf,
            slice: buf.slice_from(0)
        }
    }
}

I understand that for this simple case, I could support offsets and manually call the cut functions:

struct Foo {
    buf: [u8, ..64],
    slice_from: uint,
    slice_to: uint
}

However, this question is simply a simplification of a more general use case for data containing a structure and references to the same data, and I wonder if this is possible (in a safe way) in Rust.

+4
source share
1 answer

, , . , ​​:

let foo = Foo {
    buf: [0, ..64],
    slice: obtain_slice_somehow()
};

slice buf, , buf, . foo :

return Box::new(foo);

foo , , . slice , , , , .

+6

All Articles