C
C
CNNRNN2020-05-23 20:11:58
Rust
CNNRNN, 2020-05-23 20:11:58

Is it possible to store pointers in an array?

Good day!
Let's say there is an array of bytes, as well as a structure with fields . I would like to know if this can be done. so that the fields of this structure point to different parts of this array.
Here is a simplified example with numbers.

// буфер с простыми числами
  let  buffer = [10,11,12,13,14];
   // здесь я хотел бы хранить четные числа из buffer
    let mut  even_numbers:[&[i32];10] = [&[0];10];
 // а тут нечетные. 
    let mut odd_numbers:[&[i32];10] = [&[0];10];
    even_numbers[0] = &buffer[0..1];
    even_numbers[1] = &buffer[2..3];
    even_numbers[2] = &buffer[4..];

    print!("{:?}",even_numbers[1]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Lesnikov, 2020-05-24
@ozkriff

You can just use slices:

#[derive(Debug)]
struct CarInfo<'a> {
    name: &'a str,
    model: &'a str,
}

fn main() {
    let input = ["vaz:2107", "gaz:3102"];
    let output: Vec<CarInfo> = input
        .iter()
        .map(|s| s.split_at(s.find(':').expect("Can't find ':'")))
        .map(|(name, model)| CarInfo { name, model: &model[1..] })
        .collect();
    dbg!(output);
}

( sandbox )
Output:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.56s
Running `target/debug/playground`
[src/main.rs:14] output = [
    CarInfo {
        name: "vaz",
        model: "2107",
    },
    CarInfo {
        name: "gaz",
        model: "3102",
    },
]

An important point to keep in mind is that in this implementation, the structure cannot outlive the data referenced by its fields.

Similar questions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question