0

I am new to rust and I don't completely understand how it works

I am trying to put what is the next county from the current one

use std::ptr::null;

struct County{
    pub id: u32,
    pub next: *const County,
}

fn main() {
    let mut counties : Vec<County> = Vec::new();
    for i in 0..10{
        let county = County{id: i, next: null() };
        counties.push(county);
    }

    for i in 1..10{
        let county = counties.get(i).unwrap();
        county.next = counties.get(i - 1).unwrap();
    }
}
  • Welcome to Stack Overflow, Lilith! :) It's notoriously hard to write a linked list in Rust the way we used to do in other languages. It's because the ownership of elements is somewhat complicated. Since the performance of linked lists is usually pretty bad, there's no ongoing effort to make them easy. But if you really want to know the details, [Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial.github.io/too-many-lists/) has all the defails you need. – aedm Jul 22 '22 at 07:32
  • @aedm would that help me too, if instead of a linked list I am trying to build a graph? – Lilith Alanis Jul 22 '22 at 08:01
  • 2
    **Please**, don't use raw pointers/unsafe code until you master Rust. – Chayim Friedman Jul 22 '22 at 08:12
  • @LilithAlanis Graphs depend. A directed acyclic graph isn't a problem, and you can use `Box` to hold the recursive children. As soon as you get cycles, though, rust has a really hard time. It's possible for sure, with weak reference counters, but it's no longer trivial. Although in general, if you want to hold the elements in a vector, like in your example code, you will run into the same problems as with a list. – Finomnis Jul 22 '22 at 08:39

0 Answers0