Hacker News new | ask | show | jobs
by d9fb698e010974b 3910 days ago
How easy is it to deal with raw memory in rust? That's the main reason for using C in my opinion.
3 comments

I don't know what you mean by "deal with raw memory" but rust allows you to do silly things like:

    let foo = unsafe { std::slice::from_raw_parts_mut(0xdeadbeef as *mut u8, 42) };

That gets you a slice (pointer+length that can be used as an array) that points to 0xdeadbeef. Bit more verbose than the c equivalent

    char* foo = 0xdeadbeef;
but arguably this is pretty rare usecase even for handling raw memory
You have to use `unsafe`, but you can do anything you can do in C. Raw pointers are the primary mechanism, same as C pointers http://doc.rust-lang.org/stable/book/raw-pointers.html
Not sure is it like this anymore, but might be worth giving a read:

> But allocating memory seemed like a fun exercise. To allocate something on the heap in Rust, you can do

> let a = ~2

> This creates a pointer to a 2 on the heap.

http://jvns.ca/blog/2014/03/12/the-rust-os-story/

That syntax has been changed, actually. Now, to allocated an owned pointer allocated on the heap, you use the Box type:

> let a = Box::new(2);

I believe it's an unstable feature currently to use the "box" keyword to heap-allocate a value, which can also be used in pattern matching. I saw somewhere that "box" will be made into an overloadable operator, such that you can easily create reference-counted and atomically reference-counted types.

Yes, that's generally correct. We still haven't fully decided on the exact syntax. If anyone wants to get involved, this RFC was the one that got merged, but hasn't been made stable yet: https://github.com/rust-lang/rfcs/blob/master/text/0809-box-...

And this is the active, in-final-comment-period one which modifies it: https://github.com/rust-lang/rfcs/pull/1228