Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding lifetime parameters in rust for a struct?

Tags:

rust

How would I go about avoiding the lifetime parameter of an already existing struct in rust? I want to use it in a wasm project, and to be able to return it to javascript I can not use lifetimes.

The following does not work syntactically, but logically I don't see any reason for it not to. A.inner will never outlive A.buf, since they are in the same struct. I can not, however, find any way to express this in rust.

struct AInner<'a> {
    parsed_data: u32,
    rest: &'a [u8],
}

struct A {
    buf: Vec<u8>,
    inner: AInner<????> // AInner.rest is referencing A.buf
}
like image 376
Qoutroy Avatar asked Jul 11 '26 21:07

Qoutroy


1 Answers

You could use Rc and share the pointer:

use std::rc::Rc;

struct AInner {
    parsed_data: u32,
    rest: Rc<Vec<u8>>,
}

struct A {
    buf: Rc<Vec<u8>>,
    inner: AInner
}

impl A {
    pub fn new(v: Vec<u8>, parsed_data: u32) -> Self {
        let buf = Rc::new(v);
        A {
            buf: buf.clone(),
            inner: AInner {
                rest: buf,
                parsed_data
            }
        }
    }
}

Playground

like image 180
Netwave Avatar answered Jul 13 '26 21:07

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!