C-pointer-like object in Rust

I'm new to rust and trying to learn it by write some code. Currently I write tetris game using piston framework

I need something like c/c++ pointer or read only reference where I can change what is referenced by the reference a.k.a pointer

I prepare some c++ code to describe for what I need this

#include <iostream>
#include <vector>
#include <random>

using namespace std;

struct ImportantObject {
    ImportantObject() {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> distrib(0, 10000);
        num = distrib(gen);
    void someAction() {
        cout << "Action !!! " << num << endl;

    int num;

struct SomeKindOfSelector {
        : objects(std::vector<ImportantObject>(10))
        , current(&objects[0])
    std::vector<ImportantObject> objects;
    ImportantObject* current;

    void next() {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> distrib(0, objects.size() - 1);
        current = &objects[distrib(gen)];

    void action() {

int main()
    SomeKindOfSelector s;
    return 0;

I hope it will give you some idea what I want

If I understand you correctly, you want to keep a reference to the "current" object as determined by a random number? In that case you are probably better off storing the index of the selected object instead of a reference or pointer to the object itself. So instead of current = &objects[distrib(gen)]; you do current_idx = distrib(gen) and you use that index whenever you need to access the current object. Using this approach, you are much less likely to run into nasty borrowing and lifetime issues.


Here’s a translation of your C++ code, for reference: (Playground)

use rand::prelude::*;
use rand::distributions::Uniform;
use std::ops::Deref;

struct ImportantObject(u16);

impl ImportantObject {
    pub fn new()->Self {
        ImportantObject(Uniform::new(0,10000).sample(&mut rand::thread_rng()))

    pub fn some_action(&self) {
        println!("{:?}", self);

struct SomeKindOfSelector {
    dist: Uniform<usize>,
    objects: Vec<ImportantObject>,
    current: usize

impl SomeKindOfSelector {
    pub fn new(count:usize)->Self {
        SomeKindOfSelector {
            dist: Uniform::new(0,count),
            objects: (0..count).map(|_| ImportantObject::new()).collect(),
            current: 0

    pub fn next(&mut self) {
        self.current = self.dist.sample(&mut rand::thread_rng());

impl Deref for SomeKindOfSelector {
    type Target=ImportantObject;
    fn deref(&self)->&ImportantObject {

fn main() {
    let mut select = SomeKindOfSelector::new(5);
    for _ in 0..10 {

thanks for your answer it is close to what I want (I'm not sure if it is possible without using unsafe).
But If I decide to use index why I would bother to use Deref trait. Isn't it simpler to implement method which hide whats going on and call internally some_action on whats in current index ?

1 Like

It really depends on what you’re ultimately going to do with this. Deref will let you use SomeKindOfSelector in many places that are expecting ImportantObject, but you don’t get the chance to intercept those calls.

Another option is to not store a current selection inside this object but instead always return a random one. You can store the &ImportantObject reference as a variable somewhere else and use it until asking for a new one.

Rust has several pointer-like types, but which you choose depends on context. "Rust equivalent of a C pointer" is a question that can't be answered directly, like "Which chopstick is the fork equivalent?"

  • Box<ImportantObject> gives you a pointer to an object that you can mutate. It's probably what you want, if your program can work with single ownership.

  • Arc<ImportantObject> is a pointer that supports multiple owners, but for shared mutability it needs to be Arc<Mutex<ImportantObject>> (Rc<RefCell<ImportantObject>> is the same type, but single-threded).

  • &mut ImportantObject is implemented as a pointer, but semantically it does not behave like a C pointer, because it makes everything touching it temporary, and locked to a single scope. It prevents the object from being moved and very aggressively enforces exclusive access. It can't exist on its own. It can only exist as a temporary lock of a Box, locked mutex, stack-allocated owned object, or similar. Apart from function arguments, it's very rarely appropriate.

  • *mut ImportantObject is literally a C pointer in Rust. It has no safety guarantees and no automatic memory management. You can use it to interoperate with existing C objects.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.