Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Everything except the two reference types (& and &mut) can be trivially implemented in libraries: Rust is a low level language.

E.g. the following is almost exactly identical to `~T`

  #[unsafe_no_drop_flag]
  struct Uniq<T> { priv ptr: *mut T }

  impl<T> Uniq<T> {
      fn new(value: T) -> Uniq<T> {
          unsafe {
              let ptr = malloc(size_of::<T>()) as *mut T;
              if ptr.is_null() { fail!("malloc failed"); }

              move_val_init(&mut *ptr, value);
              Uniq { ptr: ptr }
          }
      }

      fn borrow<'a>(&'a self) -> &'a T {
          unsafe {&*self.ptr}
      }
      fn borrow_mut<'a>(&'a mut self) -> &'a mut T {
          unsafe {&mut *self.ptr}
      }
      fn move(mut self) -> T {
          unsafe {
              let v = ptr::read_ptr(self.ptr as *T);
              free(self.ptr);
              self.ptr = 0;
              v
          }
      }
  }
  #[unsafe_destructor]
  impl<T> Drop for Uniq<T> {
      fn drop(&mut self) {
          unsafe {
              // this will free the pointer and run the 
              // destructor of the inner type
              replace(self, transmute(0)).move();
          }
      }
  }


Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: