Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a null pointer in a struct?

Tags:

struct

rust

How do I create null pointer properties in struct like in C++? I do not quite understand how to make a pointer to an empty space in the memory.

C++

struct test{
    string data;
    assocc *el;
}
srtuct assocc {
  T *data;
}

Rust

struct test {
     data: String,
     ponts: *const Option<assocc<T>>,
}

struct assocc<T> {
    data: T,
}

impl test {
   fn new(data: String) -> test {
      test {
          data: data,
          ponts: None,/*This don't work*/
      }
   }
}

impl<T> assocc<T> {
  fn new(data: T) -> assocc {
      assocc { 
          data: data,
      }
  }
}
like image 897
Alexsandr Startsev Avatar asked Aug 18 '16 19:08

Alexsandr Startsev


1 Answers

There are a few issues with your code. To start out, Rust type names are generally CamelCased, so let's start with that:

struct Test {
     data: String,
     ponts: *const Option<Assocc<T>>,
}

struct Assocc<T> {
    data: T,
}

Next, because Test is enclosing something with a generic type T, it itself needs to be generic:

struct Test<T> {
     data: String,
     ponts: *const Option<Assocc<T>>,
}

struct Assocc<T> {
    data: T,
}

Unless you're doing FFI where you absolutely need to store a raw pointer, it's probably better to just have your Test struct own the Assoc:

struct Test<T> {
     data: String,
     ponts: Option<Assocc<T>>,
}

struct Assocc<T> {
    data: T,
}

And some of the types in the impl blocks need to be changed around to add some generics:

impl<T> Test<T> {
    fn new(data: String) -> Test<T> {
        Test {
            data: data,
            points: None,
        }
    }
}

impl<T> Assocc<T> {
    fn new(data: T) -> Assocc<T> {
        Assocc { data: data }
    }
}

Finally, let's add a main function to ensure that we can actually use the structs as we're expecting:

struct Test<T> {
    data: String,
    ponts: Option<Assocc<T>>,
}

struct Assocc<T> {
    data: T,
}

impl<T> Test<T> {
    fn new(data: String) -> Test<T> {
        Test {
            data: data,
            ponts: None,
        }
    }
}

impl<T> Assocc<T> {
    fn new(data: T) -> Assocc<T> {
        Assocc { data: data }
    }
}

fn main() {
    let mut t = Test::new("Hello!".to_string());
    t.ponts = Some(Assocc::new(32));
}
like image 200
Lily Mara Avatar answered Oct 08 '22 13:10

Lily Mara