简体   繁体   中英

Avoiding lifetime parameters in rust for a struct?

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM