If you were to ask me 2 weeks ago if I have any interest in learning a new programming language, I’d have outright said ‘No’. Not that I am any shy to learn new technologies or languages, but because I was too misguided in my own thinking that Python for data science and Java for resilient applications have become pretty much the status quo and that any innovation in the compute space has to be with compute clusters and scalable databases.
It was not until I decided to learn blockchain and smart contracts that I happened to cross paths with Rust. Actually, my first stop was at Solidity, a language on which Ethereum blockchain is built. However, Solidity didn’t sit well with me. The syntax felt verbose and documentation seemed scarce. Then along came Rust and I am smitten with this language ever since.
To describe Rust in one sentence: C++ efficiency and Java’s robustness, only better!!
I have a Github repo dedicated to all things Rust learning here. Feel free to git clone and compose up to get Rusty!
Hello world ….
Rust Resources
The Book: Rust fundamentals to advanced concepts - all in one!
I try to share some of the topics that I found intriguing in Rust especially coming from Java, Perl and Python background. An FYI - I will continually update this post with more and more snippets as I go.
Variables - Immutable, Mutables & Shadowing
Compilation error:
x = 2; // errors out since x is immutable
^^^^^ cannot assign twice to immutable variable
Constants
Compilation error:
const SECONDS_IN_DAY: usize = get_seconds_in_day();
calls in constants are limited to constant functions, tuple structs and tuple variants
A Tuple can be heterogeneous. A tuple has to be fixed in size. Tuple values are accessed using either dot notation or by unpacking. A tuple can be empty - (). Tuples get stored on stack.
Vectors are homogeneous and they get stored on heap, which means they can grow/shrink in size. The elements in vector can be accessed using [] or with get method, for example, v[0] or v.get(0).
Output:
[1, 2, 3, 4, 5]
["Hello", "world"]
Hello
Hello
Index out of bounds error.
Output:
Hello there, mate!
Hello there, mate!How are you?
Hello there, mate!-How are you?-Hello there, mate!How are you?
How are you?; Hello there, mate!How are you?
String indexing and slices
Output:
Hello
Hello there
String indexing doesn’t work in Rust because under the hood it uses Vec<u8>. Since, they support UTF-8, a character can be more than 1 byte.