Rust Tutorial #3 - Variables, Constants and Shadowing
By Tech With Tim
Summary
## Key takeaways - **Variables Immutable by Default**: By default in Rust all variables that we define are immutable, meaning we cannot change them and cannot reassign a value to it without redeclaring the variable. The way we would fix this is by putting the keyword mut here, now mut stands for mutable so by default it's immutable but we can explicitly define this is going to be a mutable variable. [04:43], [05:04] - **Rust Does Type Inference**: Rust is a statically and strongly typed programming language so when you define a variable it's going to be given a type, you can explicitly define that type or you can let the compiler implicitly decide the type. Here this is what's known as an implicit type assignment because we're not manually specifying what the type of x is but at compile time the compiler is going to see that x is storing an integer and implicitly assign the type of x to be i32. [01:34], [01:57] - **Shadowing Redeclares Variables**: What i'm actually doing here is creating a brand new variable that has the same name as x and i'm just assigning it now to the value 5, so i'm kind of overriding in a sense this previous variable and just giving it the same name. When i say let x equals 2 inside of a different scope x is only equal to 2 inside of these curly braces, as soon as we come outside x is no longer equal to two. [07:04], [09:34] - **Shadowing Enables Type Changes**: When you're using this let and you're redefining variables you can change their type so when i do something like let x equals hello this will actually work fine because i'm redefining x so x is now a new variable it's going to get a new type the new type here is going to be string. However if i tried to do this right where i have mutable and then i run the code now you're going to see that we get an error it's expected integer but found the type of string. [11:03], [11:44] - **Constants Are Rigidly Immutable**: A constant is something whose value and type cannot change throughout the entirety of the program once it's defined, the convention when you write a constant is to write the name in all uppercases separated with underscores and you also have to specify the type of this constant. Unlike a variable you cannot reassign or kind of redefine this constant once you create it once it's there you cannot change it you cannot redefine it. [12:27], [14:18]
Topics Covered
- Variables Immutable by Default
- Redeclare to Shadow Variables
- Scope Changes Shadowing Behavior
- Constants Never Redeclarable
Full Transcript
[Music] hello everybody and welcome to video three in this rust programming tutorial series in this video i'm going to be showing you variables now i know that sounds basic i know many of you know
variables but they work a lot differently in rust than in other languages so make sure you stay tuned and pay attention to all of the details because there is quite a few and it's pretty fundamental to understand this
before moving forward if you guys are enjoying the series please do leave a like leave a comment let me know you'd like to see uh in the future of this series i myself am no rust expert i've just been learning the language for a
few days and obviously i feel qualified enough to teach you kind of the basic stuff and go through some of the cool features so with that said we can dive in here i will mention though i do have a programming course programming expert dot io if you guys haven't yet just
check it out from the link in the description even if you don't want to purchase it i'd love to hear your feedback on the course what you think of the curriculum so far we've had great feedback from people that have actually purchased it and well if you want to
become a software engineer learn advanced programming and all that stuff check it out from the link in the description and use discount code tim okay so let's get into this here uh what i want to start with is
variables so how do we make a vary well to make a variable there's a few ways but the first way is to do something like let x equals and then we can go with something basic like before so there we go we've just defined a
variable the name is x and it is storing four now the first thing we need to understand here is that rust is a statically and strongly typed programming language what that means is
that when you define a variable it's going to be given a type now you can explicitly define that type meaning you actually write out what the type is manually or you can let the compiler
implicitly decide the type so here this is what's known as an implicit type assignment or type decision because we're not manually specifying what the type of x is but at compile time so when
the compiler starts running it's going to see that x is storing an integer and it's going to implicitly assign the type of x to be a type int i'm going to get into data types in the next video so
stay tuned for that but just keep that in mind you have explicit and implicit and by default when you're doing this it's implicitly assigning the type and what that means is you cannot change the type of this variable
throughout the program so in python for example you could do something like let x equals four you wouldn't have black keyword but you'd have x equals four and then down here you could just go x equals
and then make it a string here that does not work and the reason that doesn't work is because you can't assign a string to type int okay now one quick thing here if you want to
explicitly define the type you would put a colon here and you would write the type so if i did something like u32 then i would be assigning this to a you int or unsigned integer 32 type um again
we're going to talk about that in the next video just want to quickly show that for anyone wonder okay so we have let x equals four let's just start by printing this out so we'll go print line exclamation point with our semicolon and
then we're going to put what's known as a formatting string so i'm going to write something like x is colon and then i'm going to put my curly braces here and then i'm going to put a comma and
i'm going to put x and what this will do is embed the value of x inside of my curly braces in the outputted string so to show you this let's just go to our terminal notice i'm inside of tutorial 3
here i just created that before the video and now i can do something like cargo run and you will see that we get oh, wait, why, are we, getting, hello, world uh i think i'm in the wrong main file
sorry about that guys let's go to tutorial 3 source main let's paste that in and let's rerun if you have no idea what i did don't worry but now we have x is four okay so that's working and
that's how you embed a variable in a string however let's try doing something that you know seems obvious that we'd be able to do but that we actually can't do if i go here and i type something like x
equals five uh obviously you're going to assume if you come from another programming language that okay yeah x is gonna be changed to the value five now it's gonna print out five but watch what happens
here when i go to my compiler and i run this notice that i actually get an error here it says cannot assign twice to immutable variable x that's my main error it gives me kind of a snapshot of the program and it actually tells me
exactly what i need to do to fix this error as well as where the error occurred so i'm actually very impressed with the error handling and messages from the rust compiler i haven't seen
anything quite this good in many other languages so just something to note there anyways the reason we're getting this error is because by default in rust all variables that we define are
immutable now immutable just means we cannot change them and so when i do something like let x equals 4 by default i cannot change x i just can't reassign
a value to it without redeclaring the variable so the way we would fix this is by putting this keyword mut here now mutt or mut stands for mutable so by
default it's immutable but we can explicitly define this is going to be a mutable variable and now this will work so i said let mutable x equals 4 and now i'm allowed to change the value of x
throughout the program because i've made it mutable okay so let's go here let's run this and we should see that we don't get any errors and we get x is four and x is five great now one thing to note
here is you may get some warnings uh in your program so for example i do this like let uh mutable x equals four and then x equals five and then i run the code it will compile but we will get some warnings so you can
see x is 5 and we're getting a warning it says value assigned to x is never read now the reason we're getting this is because we've defined a variable x here we've then changed the value and we
didn't really need to do this this is kind of illogical code right really what i would do is change it to be like this so we just directly assigned to x because
why am i writing x equals 5 down here it's kind of hard for me to really articulate it more than that but that's why we're getting a warning because we kind of have code that's not really necessary now when we run this code
well it's clear and around again we're going to get another warning and says variable does not need to be mutable that's because we're not changing x so we don't need this mutable keyword so if
i remove this now and rerun of course we are going to get uh compiling with no warnings okay so that was the basics there on variables now let's see how we
actually change the value of x without making it mutable so what i can do is something like let x equals five now at first glance you're going to think probably if you're coming from
another language that i'm gonna get an error here and the reason you would think that is because i'm redefining a variable that already exists in this scope scope just being the function that i'm writing however this is actually not
a problem in rust and when i go and compile the code here you're going to see that this is completely fine i get x is 4 and x is 5. now the reason for this is i am actually allowed to kind of
recreate x here what i'm actually doing here is creating a brand new variable that has the same name as x and i'm just assigning it now to the value 5. so i'm
kind of overriding in a sense this previous variable and just giving it the same name which in this case it's five so now if i go here and i run this
you're gonna see xs4 xs5 no problem whatsoever and that's one of the ways you can get around that kind of mutability issue right because if i had x equals 5 then i would need to make this mutable but if i don't want to make
the variable immutable then instead what i can do is just redeclare it using the let keyword and similarly i can do something like let x equals x plus one and now i'm going to increment the
previous value of x and assign that to a new variable called x and there's no problem doing this so let's go here and rerun and notice that xs4x is five no problem
whatsoever ok so that was the first thing to show you the next thing to show you with this kind of way of declaring variables is what happens when you have kind of name
shadowing from different scopes now if you're unfamiliar with name shadowing essentially this means you use the same variable name but from a different scope now a scope we can kind of think of as these indentation levels
here in the curly braces we'll get more into them later when we talk about functions and all of that but let's have a look at this example so what i could do is just make my own scope now i'm just making a scope by
putting a set of uh what is it curly braces here you don't have to worry about exactly why this works but let's watch what happens when i do something like let x equals two then i say fmt or fmt i'm thinking of go
here print ln exclamation point and then i put x is colon i really could have just copied this i guess and then x
so just take a guess pause the video if you want and tell me what you think the output of this program is going to be okay so i'm going to run the code now let's go here let's run this and notice that i get x
is 4 x is 2 and x is 5. now you can kind of have a look at them side by side here i'll, put, it, to, the, right, it's, a little bit weird why we're getting this right you might have imagined that what was
gonna happen is we'd get x is four x is two and then x is three and the reason you'd probably guess that is because we're saying let x equals two well when we do that you'd think x is going to
change right we're redefining x now the reason that doesn't happen is because we're saying let x equals 2 inside of a different scope so let me go back to the code here so this and this are in the
same scope this is kind of an interior scope to this this main function so what that means when i say let x equals 2 x is only equal to 2 inside of these curly
braces right here as soon as we come outside x is no longer equal to two uh that's just not it's only equal to two here when we come outside x is equal to
four because inside of that scope that's what we define x to be equal to i know seems kind of weird uh but that's really, how, it works, when, i, define, it, in this scope it's not being changed in the parent scope it's only being changed in
this current scope so when i come down here we're reusing the previous value of x not the one that was defined in the interior scope now though let's get even more complicated and let's do something like
x and actually let's just go minus 2. so
now again take a guess of what you think the result is going to be i'm about to run the code let's go cls and cargo run and notice i get x is 4 x is 2 and x is 5. now the point of this example is that
5. now the point of this example is that i can use the x from the exterior scope in the interior scope right so this is exterior this is interior i'm able to
access this x from inside of here and use it totally fine that's all right but again it doesn't change the x outside because i'm defining it inside of this scope, we'll, see, a lot, more, of, examples of this later on but that is what i
wanted to show you here in terms of kind of the name shadowing and the i don't want to call it strange behavior but the behavior that occurs when you do this okay so that is the basics on variables here
one more thing to have a look at is that when you're using this let and you're redefining variables you can change their type so when i do something like let x equals
hello here if i close my uh what, do you, call, this, my, double quotation mark this will actually work fine so if i go back here and i clear and cargo run notice we don't get any
problems and we're printing out hello now that sounds contradictory to what i showed you before but the reason this works is because i'm redefining x so x is now a new variable it's going to get
a new type the new type here is going to be hello and this works completely fine so sorry the new type is going to be string not hello but it is string because we put hello here so this was an
int this is a string however if i tried to do this right where i have mutable and then i run the code now you're going to see that we get an error it's expected integer but found
the type of string hopefully this is kind of coming full circle but since i'm not making a new variable i'm trying to mutate an existing one i can't change the type but if i just go let x creating a new
variable i can change the type and that's completely fine okay that's almost everything i have to cover last thing i'm going to cover is constants so a constant value
might seem very similar to a what is it an immutable variable it is actually similar but the construct and kind of the sort not the construct the convention on how you write it is different and there's a few rules that
you need to follow so when you use this const keyword you're actually creating something called a constant right you're not creating a variable a constant is something whose value and type cannot change throughout the entirety of the
program once it's defined so let's just have a look at some examples here the convention when you write a constant is to write the name in all uppercases separated with underscores so i could do
something like seconds in and then minute and this is how you're actually supposed to write it so all capitals uh you do again using underscores instead of kind of camel case and this is actually referred to as
i think it's capital snake case or something like that now when you define a constant you also have to specify the type of this constant so i have to do something like say u32 standing for
unsigned integer 32 and then make this equal to a value i need to define a value for it i can't leave it kind of blank right so here i'll just go with 60 and put my semicolon now that we can print this out
so let's say print ln exclamation point and let's just do kind of an empty formatting string here and then do second in minute okay so let's run this cargo run
and notice that we get 60 no errors everything is working fine however if we were to remove this type we would get an error and if we try to change this right seconds and minutes is equal to 100
and i go here we'll get an error it says cannot assign to this expression because this is a constant now same thing if i do something like const let's just redefine this and
change the value here and let's see what we get okay so let's go let's clear cargo run and notice i get a problem oh it's saying it didn't find a
semicolon so let's just fix that first before we look at the other error okay clear and run and again i still get this problem it says seconds and minute is defined multiple times so unlike a
variable you cannot reassign or kind of redefine this constant once you create it once it's there you cannot change it you cannot redefine it okay so i think with that said i am going to end the video here i know i
didn't show you that much but there was a lot of details related to the variables into the constants and i wanted to spend some time on this to make, sure, it was, super, clear, because there is a lot to kind of unpack here with a strongly and statically typed
language especially if you're unfamiliar with that in the next video we'll talk about data types we'll start to clear some of this up then we'll get into console input and if statements and all the other kind of cool features that
rust has that other languages don't if you guys enjoyed make sure to leave a like subscribe to the channel check out programmingexpert.io and i will see you
in another one [Music]
Loading video analysis...