DEV Community

Cover image for RustLings I

Posted on

RustLings I

Hello again! I had a nice sleep :))

Today we'll learn how to use variables in Rust :D

Oh yeah! Something you need to know is that all exercises of variables have been done by my little sister of 10 years xd

Just for you to know SJSJJSSJJSJSJ

In the first file of rustlings we get an error that simply means, x does not exist and that's because we haven't defined the variable.

So... the way to define a variable is using the keyword let

let x = 5;
Enter fullscreen mode Exit fullscreen mode

Something you need to know is that when you create a variable it has to be defined, otherwise you will get an error from the Compile.

OH YES!!! Another important thing is that every variable you create is inmutable. What does it mean? That you cannot change the value of the variable. To make a variable mutable you have to use the keyword mut before the name of the variable.

let mut y = 0;
y = 2;
Enter fullscreen mode Exit fullscreen mode

Something you can do is telling a variable what type it is. (You have to do this in the second variable file)

So if you go to the docs ->

Go and read :)

let x: i8 = 1;
Enter fullscreen mode Exit fullscreen mode

That is an example :D

Now an interesting "tool" is that you can change the type of a variable, is what they call "shadowed".

I think you will understand if I give you an example ->

let random = "OH YEAH I AM A STRING";
let random = 5;
Enter fullscreen mode Exit fullscreen mode

Yeah is... strange??? I mean, you change the type of the variable just using the let keyword and the same name of the variable. And is super weird (for me at least) but I think is useful, but IDK, we'll see.

Also it is called shadowed because is like the first initialization of the variable gets "shadowed" by the last one.

The constants in Rust... you have to specify the type, otherwise it won't work.

const PI: i8 = 3.14;
Enter fullscreen mode Exit fullscreen mode

And the best for the end... Why the f* I have to use mut if I have constants???

Well... let me read the docs...


  • You cannot use mut with const I think is something obvious.
  • const needs to have a type, let no
  • const can be used in any scope, including global
  • let can get the result of a function or something like that, but const can't, it has to be a value.

Something like this, I think it convinced me, I mean, having variables that are immutable is "top" you can do a lot of things with it, some times we have variables that never change their value, and this is like a "plus" for rust, I cannot think about any example now, sry.

So this is all for today, I wish you a nice sleep or end of reading, or whatever you want.



Follow me!

(I liked more the red bird :_()
🐦 Twitter
🐙 GitHub
👥 LinkdIn

Discussion (0)