Rust Notes: From A C++ User
Learn Rust from C++ programmer’s perspective
loop
If we have a vec
:
1 | let vec = vec![1, 2, 3]; |
for range
1 | for i in 0..vec.len() { |
for each
1 | // type of `item` is &u64 |
If vec
is not used as reference here, there will be an implicit move:
1 | //`vec` moved due to this implicit call to `.into_iter()` |
Or we can use iterator, which is not exactly same as we do in C++:
1 | // type of `item` is &u64 |
Or use enumerate
, same as we do in python:
1 | for (index, item) in vec.iter().enumerate() { |
dead loop
Same as while(true)
:
1 | let mut i = 0; |
Heap
To allocate memory on heap, use Box<T>
:
1 | let x = Box::<usize>::new(20); |
Box<T>
is very similar to std::unique_ptr<T>
in C++. const auto x = std::make_unique<const int>(123)
can be written as let x = Box::new(123)
in Rust.