English 中文(简体)
如何在另一个结构相同的领域找到一个构件?
原标题:How to get the address of a struct element in another field of same structure in rust?
  • 时间:2024-04-10 02:32:56
  •  标签:
  • rust
struct CirBuffer {
    buf: [u8; 256],
    lowest_mem_addr: *const u8,
    highest_mem_addr: *const u8,
    is_empty: bool,
    is_full: bool,
}

构造项目lowest_mem_addr 是佩戴面罩。

impl CirBuffer 页: 1

fn create () -> Self{
    CirBuffer {
        buf: [0;256],
        lowest_mem_addr: &(*self).buf[0],=> How to get the address of buf[0] here ?
        highest_mem_addr: &self.buf[255],
问题回答

也许我没有东西,但难道这只是一个在结构之外宣布缓冲的问题吗?

struct CirBuffer {
    buf: [u8; 256],
    lowest_mem_addr: *const u8,
    highest_mem_addr: *const u8,
    is_empty: bool,
    is_full: bool,
}

impl CirBuffer {
    fn create() -> Self {
        let buf = [0; 256];

        CirBuffer {
            buf,
            lowest_mem_addr: &buf[0],
            highest_mem_addr: &buf[255],
            is_empty: true,
            is_full: false,
        }
    }
}

简言之,由于同样的原因,自食其力的建筑不奏效。

Rust的任何类型都假定是三维的动产,即,你总是可以打电话到<条码>>mcpy on thelying bytes,忘记了原样,并且将本拷贝用作正本,而且一切工作都应该是作为人。 但是,如果你认为你的点人是有效的(如果你重新创建,为什么会 t你?),那就会打破——点人仍将指老的立场,现在这种立场正在 d。

取决于你想要的:

  • Just use VecDeque. It would be good enough for many practical cases.
  • Put the buffer on the heap, as Box<[u8; 256]>. In this case, you must be careful not to move this buffer out of the box - in particular, you must never expose a mutable reference to buf, since caller might then simply mem::swap it. There might be another considerations - I m not an expert with unsafe code, better have a review from more experienced programmers.
  • Use indices instead of pointers. You might want to store them as u8 and use buf[idx as usize], since in this case bound checks will be optimized away - check "Show Assembly" in this playground.




相关问题
Creating an alias for a variable

I have the following code in Rust (which will not compile but illustrates what I am after). For readability purposes, I would like to refer the same string with two different names so that the name of ...

Rust Visual Studio Code code completion not working

I m trying to learn Rust and installed the Rust extension for VSCode. But I m not seeing auto-completions for any syntax. I d like to call .trim() on String but I get no completion for it. I read that ...

热门标签