This video provides a comprehensive introduction to Rust programming language fundamentals specifically tailored for developers interested in building Solana smart contracts, covering essential topics including installation with Rust and VSCode, basic syntax with Cargo for package management, scalar types (integers, floats, chars, booleans), arrays and slices, tuples, functions, mutability, structs, traits, enums, vectors, hash maps, options, and results, all demonstrated through practical examples relevant to blockchain development.
Rust Crash Course for Solana Smart Contract Development
Added:hey everyone this is josh and this video we're going to go through a quick run-through of everything in rust to help you get started writing programs for the solana smart contract blockchain i myself just personally started dabbling in solano just recently however after playing around for a week or two now i feel like i have enough information to give a quick functionality walkthrough for more experienced developers to quickly pick up breasts so i can start writing solana's smart contracts first things first what is rust rust is a statically typed programming language that's designed for both performance and safety specifically in regards to concurrency and memory management it's very similar to c plus and it's an open source project that's developed by mozilla research i.e firefox as you might imagine if anything that's related to c plus plus rust is used for low level system programming and scenarios where you want highly performant applications if you're watching this specific video the most important part of rust is that it is the programming language of choice to write solana smart contracts so first to get started we're going to install rust and our ide with visual studio code if you have all this installed already just look at the timestamps in the video and just skip ahead the first thing we need to do is install rust so it's pretty straightforward we go wrestling.org and then you just hit install and then download the ext if your windows download the installation exe windows or use curl to install the windows subsystem if you have that we'll actually be using that later on in the future i'm not gonna walk through this process i'm sure we're all big boys and girls and know how to do this now that you have rest installed you need a tool to help you write code for rest my personal recommendation is visual studio code go to code.visualstudio.com and download and install it now in my case i already have it installed one quick thing i would highly recommend once you have your visual studio code open is to go to your extensions which you also open by ctrl shift x and just look for some rust extensions specifically just the official rust for visual studio code as you see i reinstalled it highly recommend it and it helps catch syntax errors and gives code snippets that you can use now that we have our ide set up we can get started with writing our first rust program in rest there are two ways we can deploy our code one is using the native rust compiler and the other one is using another tool called cargo which is similar to npm if you have ever used that for javascript before so to get started we're going to create a restrict first so we can just go to we just create a new folder i'll just make one it can be anything i'm just going to make a new folder right here and i'll just call rest go in here and so we'll be creating a workspace yes i trust this folder so i'll be creating a workspace in this folder and so the first thing is i'll just go to file new file and i'm just going to paste it starting hello road code inside this folder i'll just call it main dot r s and so this is the basic skeleton of a red script similar to other object-oriented programming languages that you might know such as java and c there's a main function that gets executed by the program where you write your code this is how you define a function in rust it's just fn for function in the name of your function your parameters and then your code we'll talk more about this later but to build this code you need your command prompt you can do control in the squiggly line or use right click and then just click open in integrated terminal this will display a terminal in your visual studio code so it's very handy and i'll just maximize the screen a bit to compile your rescript you can just simply do rest c and then the name of your rest file so this will build and compile and as you can see if i do a dir as you see there's a new main.exe that has been created and to execute the code you just type in exe and then you see hello road and this is the basic of writing compiling and running risk code this might work for a small application but as you imagine once we build bigger applications we're going to have a lot more files and a lot more dependencies to manage and that's why rust has something called cargo cargo is rust package management system and like i mentioned earlier it's very similar to npm for javascript or pip for python and to create a cargo project it's pretty straightforward when you install rust cargo should actually should automatically come with it and to create a new project you just need to in your command prompt type cargo new and then just your project name and so i'll just call it hello and as you see over here my folder directory there's this new hello folder that opened up and if we quickly just go through it you'll see that we have our main rs and extremely identical to the code that we wrote originally this is your basic hello road function what i do want to bring attention to is this cargo.toml file this essentially is your package manager file think of this as your package.json for npm in this file we have information about our application that we're writing and we can also list any dependencies that we want to download and install in this video we're not going to include any dependencies but you imagine later on when developing salon smart contracts you'll need to have a dependency for all the salon libraries that we need to use to quickly build your application for cargo there's two ways you could do cargo build well i need to go inside my new uh cargo project i created okay now if you do cargo build this is very similar to like a npm run build it just compiles and build your code make sure it works and if you look inside the target folder and go inside debug you'll see that this hello.exe has been created now as you can imagine this gets annoying because you have to build every single time and then execute the code now if if you want to compile the code and execute at the same time you just type in cargo run it'll build the code and then it'll run it and this is roughly all you need to know to get started building and writing a rest application let's start actually diving into the code so go back to our main rs in our hello folder this is very important uh because we want to use cargo let's close the old one before giving a quick overview of the variables first we need to know is how to print string onto the console and for that similar to java actually russ has a println macro this isn't a function i want to call out it's a macro and you can identify if something's a macro with the explanation mark so rust comes with these reset macros that will execute some code for you and what println does is it prints onto the console the string that you give it and then it creates a new line now if you want to include variables one unique thing about printing the console on rust is that you actually need to get if you want to include variables you need to actually add these open and close curly bracelets and we'll just make some simple integers um nothing too hard so just create two integers a and b and you know there's 10 and 15. and so print line works kind of like a print f if you work in other languages these curly braces represent a variable and there are many different ways of representing them this is the simplest and so the macro takes in the string and it automatically looks to make sure that there is a exact amount of variables that you pass that corresponds to the curly braces so we just do a and b and then save and then if you do a cargo run you see that the hello road has 10 and 15.
now that we're talking about variable types that'll be a good segue into seeing how russ handles variables our scalar types or our primitive variable types we have four scalar types or you can also them as primitive types and those are our integers which are two of uh there's our floats there's our characters and there'll be booleans so looking at our integers there are two types of integers there are unsigned integers and there are sign integers for those of you who are familiar with c c plus plus you should feel right at home here but essentially a unsigned integer means the number cannot be negative that's why it says it's unsigned there's no sign while a signed integer is a number that can be negative and so unless you define a variable by using the keyword let you give it the variable name and then you give it the type but because rust can actually dynamically infer we're using you don't actually need to even include the variable name for example if i just get rid of this it would still work working compile so just to dive into a bit of a finer point into the representation of this we have u8 which represents a unsigned integer that has eight bits and so these numbers 8 16 32 64 128 these are the size we can store our variables in ideally we want to use the smallest amount of bit possible to conserve the space teachers that we have in this example we're just using u8 so one thing to note is if i try to make this variable negative you see that again error here saying that i can't you apply the unitary operator minus sign to type u8 it has to be positive and likewise if i try to make this variable bigger than eight bits which i don't know the exact number again but let's say a thousand we get another error saying that one thousand is out of the range of uh um oh it says right here the range is from zero to fifty five now for the sign integer it's exactly the same thing uh you use i to represent signed and then the number afterward is the number of bits that's used now if you look at the chart right here the one big difference between unsigned and signed integers is that in sign integers the last bit is actually used to indicate if the value is negative or a positive number so outside of that it works exactly the same likewise for example over here if i just make this number bigger the range is from negative 128 to 127 and that's basically all we need to know about integers next up is floats floats are used for exactly one thing and it's to represent decimals so right here we have one point two of course it can be a whole number two if we wanted well okay fine one point zero if i wanted to be a whole number and that's about all i have to say for floats next step we have characters or chars well this code won't compile but the chars are just essentially you think of just one character of a string uh we'll talk about strings later but this is not a string i don't have much to say in rust except it represents the same character rest also supports unicode such as this which is the happy face and i'll even just run the code right here just to kind of see what the output is so and see from our assigned example we already have the numbers that i printed for the letter example we have our c and we have our smiley face emoji and of course no programming language is complete with a boolean which is either true or false so these are our scalar types pretty straightforward and nothing too complex mathematical operations are the same for example if you want to add something 10 plus 10 minus 30 times 50 well okay these numbers are too big but these are all the same if you have any experience developing there should not be any surprise to you boolean is also the same you can do true and false or true for example now that we've gone through the scalar types the other types of variables we have are compound types such as arrays and tuples and just go through a quick example of arrays so arrays work exactly as you expect from most programming languages some things that you might get used to is how you define the array here's an example we have an array variable r which is a array of u8 integers and it has a length of three and to create an array uh it's very similar to any other languages likewise another way of quickly creating an array and you could also use a similar syntax that we defined that we use to define the array type you include the number that you want to populate the array with and then you give it the number to represent the length of the array that you want to create some of the most basic operation works exactly the same as any other language arrays and rest are also zero based indexing and if we want to refer to a specific index we just use the square braces like we do over here and this gives the first element of our array and if we want to get the length of the array it's actually pretty similar in python in this case where we use the length function which would give us the array if we want to actually print out the whole entire structure of the array we need to use a special syntax for curly braces this colon question mark that will print everything out on the right so if we run this application again you see that our value at index zero is one which is the case and that our other array has a length of five which is indeed the case that's what we set and then we look at the content of the other array we see that we have an array of five one hundreds which is exactly what we want to do we will come back to talk a bit more about arrays later specifically slices which is an important concept for solana smart contracts however i first want to go over the concept of pointers and memory management before we do that next up are tuples and once again just paste this with the screen figure for those familiar with python tuple is something that you might see commonly um it's a data structure that holds two elements in this case in rust a tuple can actually hold unlimited amounts of elements similar to an array how the difference is that a tuple can hold multiple elements of different types together so for example in this code right here i have a tuple and the tuple contains three elements a integer a boolean and a float alternative we actually don't have to define the type we can let russ figure it out and by just creating a tuple simply to create tuples you just use parentheses and to access the data types and tuples it's similar to array where you use the index but instead of using brackets you just use dot and then the index that you want and of course we can also print out the tuple and one final thing to note about tuples is that you can do these structuring if you worked in texture before this might be familiar to you but essentially all the structuring does is that you extract out the parameters inside your object or tuple in this case into individual variables so for example a b and c will be represented as 5 true 2.1 i'll print this code out and we'll see that will be exactly equivalent so let's do cargo run and you see that our first tuple over here is the equivalent of our these structure variables and so that's tuples in a nutshell next up is creating functions so let's get through this we had a helper function over here so what in this example i want to return a function that given a number we would return if it's even or not so we just print out that value it's a parameter and we'll just call is even and let's give it a number and we'll say two which is indeed even so we see that creating a function russ is not too different from your statically typed languages you define your function name in this case by default all of rus functions are private unless you explicitly set the pub which makes it a public function in the parameters you receive it's formatted by the name of the variable and the variable type and then the type we return is represented by this arrow and then the return type now what's interesting is if you look at the definition of this function what i did was to tell if a number is we just look at the number in the single digit and we can do that easily by just plotting the value by two and then and then i stored it in the digit variable and what's interesting to note is in rus to signify that you're returning a variable you simply just write your statement and then not include the semicolon as you see right here in all instances you need a semicolon to end your statement unless it is the return value of a function so this is the return is even our return bool and so just for completeness if our digit mod 2 is 0 that means that it just is even and if it's not then it has to be odd and so if we just do a cargo run again on this we can see that i didn't save it and then again we can see that this returns true because 2 is even and we give it one we can see that it returns false that's roughly all you need to know to define a function next i want to talk about mutability this is something a bit more rest specific so we're finally talking about something new so in most languages the variables that you assign they are immutable specifically meaning that you can't change it and that is actually still the case in rust however rust tightens that condition even more specifically let's say if we have a number and we'll just call it five in most languages you can change your number to be another value and then that'll be it however and rest that is actually not the case if you try to you try to run this code right here you'll get you actually perform your running you'll get an error you'll see that you cannot assign twice to immutable variable num to make everything run concurrently safe rest enforces variable mutability which prevents you from being able to actually modify the data type if you want to change a variable you just use the keyword mute in front of the variable this tells the compiler that you want to change your variable throughout your code for example maybe if you have an if statement and it's following some condition you want to have your variable be one thing otherwise have it be something else we see an error here and it's just saying that i never used the original value before i resigned it but that's okay we can ignore that and run the code and of course never save right so as you can see in our print statement we print out the value three and that's basically immutability in a nutshell all right diving even deeper into some of the rest mechanics we're going to talk about arrays slices and the concept of ownership and borrowing a quick thing about arrays and later we'll talk about strings is that let's say we make an array in most modern languages there's a concept of reference and a concept of value so an array is a reference because we're not actually pointing to the value itself we're pointing to the address and memory where the array is located on so this is an array so what is this slice well a slice is actually a very similar thing to an array a slice is also so that's an array so we don't know what an array is but what is a slice a slice you can essentially think of is a sub array so we can make this bigger in our variable called slice and essentially it can be something like we want index we want to create a subarray of index one all the way to index three not counting index three so the first value is inclusive and the last value is exclusive so this would create us a sub array of one and two and two here slice we need to de-reference our array like so and now you see that risk quickly goes away so we might ask what exactly is the difference the difference is that for an array we know the length by compile time however for slices we don't know the length that's roughly the only difference so why am i talking about this well in solana smart contracts a lot of the data that we pass in from the front end comes through a slice so essentially we're just given a random array of values that we don't know the exact length of so from all the examples i looked at what you had to do is you had to parse the slice that you get and get the and extract out the variables that you want to use not a fun process but i found that there are existing helper libraries that help you do this but that's in a much future video but now that we have an arrangement slice i'll show you some of the differences in how you define them or represent them in functions so here's a helper function called borrowing slice it takes in two parameters it takes in the original array that we created and the slice that we generated and now we just do some pretty simple printing so like we mentioned a in array you have to define the type and you have to define the fixed size of the what meanwhile if you look at a slice the ampersand references the memory that our array is pointing to and of course we give it the type which is u8 but because we don't know the length of it we don't include the semicolon so we'll just call this function we'll pass in our array and we'll pass in our slice so what this code does is it will print out the value of our array it'll print out the value of our slice it'll give the length of our slice because remember our slice is exactly the same thing as an array the only difference is that we don't know the length of the array in compile during the compile time so we can still do things like reference specific indexes we just need to know the length ahead of time and so right here you see compile error because the length is not correct like i mentioned the hat the length has to be the same so all i need to do is swap the six to four and the arrow goes away so for all that let's run the code so as you can see our array is zero one two and three we got the slice from our first index to our second index because remember this this three index three is exclusive and so that gives us a sub array of one and two and remember to get a pointer to our subarray we need we always need to use this ampersand and then finally just to prove it to everyone a slice does have a line function like an array it has a length of two and you can still reference the indexes the same way just note that index 0 is the first value of our subarray we created which is 1.
so it's not tied to the index of the whole array next up i want to talk a bit about strings at this point you might notice we talked about individual characters in a string but we haven't actually talked about how we can create a string in rust so naively let's just get rid of all this we could create a string and that can be something like hello road like so into the string and the type of this actually if actually if you just highlight it will tell you it is a ampersand string it's a string literal or basically this is actually similar to a slice it's a string slice specifically it is a reference to a space in memory that holds the constant hello road now if we want to actually create a string we can create a type string with a capital s and this is actually an object or structure that we have to create ourselves we use a we use the string and string class a struct and that and then the two colons is used to reference a function from the class and we have a function called from and then we just type the string that we want to use or to grade so let's create a string object that has a text hello this string type you can think of is equivalent to a vector it is a dynamically sized array that you can keep adding more entries or remove from it so there are a couple things you can do from it with it first thing is that if we want to get a slice we can do the exact same thing with arrays we just get the pointer of the string at a certain range of the array so here's the nursing test i might not have seen before we have dot dot six this means get everything from index zero up into index six not including index itself so in this example would be zero one two three four five six so it'll include the word hello in space and just like a regular slice from an array a string slice has the same basic function that a string has it has you can get the length of it now the string class itself has a bunch of helper methods that's associated with a couple that you a couple useful ones are string dots push which allows you to add a character so that can only be like one letters you can also do things like string dot push string which it allows you to put in a if you look at this type a string slice which essentially is just a string so this can be anything hello wrote and put an explanation mark space and bob or something now you might notice that there's a red error and what's really nice is that it tells you what there is it says cannot borrow string as mutable and what that is basically saying is that we can't modify our string because it is a immutable type we can easily fix that by just setting it to be immutable type and now the error goes away like i mentioned earlier there's a whole bunch of methods that are associated with the string object so that's how we add to a string there are other helpful functions like string that replace for example we want to replace the word hello with by for example um this function actually if you look at the vs code which is very helpful actually returns a string so what we need to do is we need to assign the result of this function call back into string itself so we'll just do a no println let's see what we get and we just pass in our string and we just save and then run and you see by road one bob we appended the word one and then we added explanation bob and then we replaced hello with the word by the string class has a lot of functions available to it more than i can quickly cover here so do look at the documentation you can quickly find by googling it and you'll get all the help you need now that we have an understanding of some of the most common variable types used in rust let's look at some of the flow controls that's available as you might expect they're not really any different from from other languages we have our if statements our for loops while loops switch statements and so on so forth so i'll just make this quick so first example is we have our if statements it's exactly as you imagined it let's say it's kind of like a python style in this if statement we just have a variable if the if the variable is greater than zero we print that it's greater than zero if it's less we print that otherwise it has to be zero so very straightforward exactly as you imagine from a typical if else if and else statement so if i just compile the code and we see that three is greater than zero which makes sense after this statement we have a for loop i would also say the for loop and rest is very similar to python we see the format here that we have 4i in and then this symbol which which creates a ray with the values zero all the way up into five this range always excludes the last value that you set in the case of rust the for loop always traverses through an array that we generate as opposed to what you might commonly see in other languages like java c sharp where you can explicitly just set a value and then set a a range that you want to iterate through so in this instance our code print values from 0 to five as you can see we go from zero all the way to five next up we have the while loop and we'll just paste it again so just like any while loops and other programming languages you have you find while and then you give the condition that you want to follow and the code will continuously execute until that condition has been met in this instance let's just say that uh we have our i value and then when i is less than four we just print the statement and then we increment it and so just to be a little bit different we can also say if i equals three we'll just print out the value first or we just print out uh exits and we can do something like break which would immediately terminate the while loop and exit the function and this works the same for for loops too alternatively there's also continue and that works the exact same way as you would expect from my normal continue it would just skip the execution of this specific iteration and move on to the next one if you have break similar to returning a value in a parameter you don't include the semicolon so if we just save this and execute our code again we'll see that we have 0 1 2 and then we exit and that's more or less the white loop and the final flow control is the match flow in other languages this is your switch statement you give it the parameter that you want to match and then you find the specific cases that you want to match and then the code that you want to execute with the case in this code here right here if we have zero we just print out the word zero if the value is either one or two the value being i we just print out one two and we can also do a range um so over here so we do three and dot dot equals four we've seen the syntax before it's what creates a range so three is the inclusive and usually four is exclusive but because we have this equal right here it's now a inclusive range from three to four which is what we print out and then finally if none of the cases match we can use a underscore to be our catch-all case which is our default so in this code right here we execute it we should just run we should bring our default correct and to prove my last point if we set four we show that it is inclusive so there you go three or four there are some more complex cases that we can use matches for but essentially the logic is the same you pass in the variable that you're matching and then you just define the cases that you want to write code for next up i want to talk about structs for those familiar c and c plus plus structs should be already very familiar to you but those who are not you can essentially think of them as classes let's get rid of this the classic example of structs we can just use uh create animals so in the case of russell's creative bird um this is how you would define a struct you just use the keyword struct write the name of the class you want and then you just define the field so let's just give it the name it just has the field string if you want multiple fields you just give it a comma and then put in the next field so maybe it's a game it has an attack or something and we give it a an integer value to be able to implement methods into your struct you simply use the keyword implement or impla and then you give it the struct that you want to add the implementation for and then inside this bracket you just define all the functions that you want so maybe one is per name what's interesting for this is that you have to define yourself similar to how you would python people familiar with javascript this might be a reference to this which references the instance of the struct that you create and so the every function that we write will have a pointer to so inside this function we'll just do a println and just give the name of the bird one nice thing i'll point out for those from the receive plus plus is that normally when you have a pointer to an object you need to do an arrow function such as this to reference the parameter but in rest that's actually all automatically handled for you so you can treat everything the same this is pretty nifty so this is the basics of creating a struct inside breast so we can just quickly use it create an instance of a structure straight straight forward you create a normal variable and then you write down the struct type and then inside brackets you have to define the type for all of your fields so that can be name bird and its attack is let's say five now this red is wrong because uh once again this this string is not actually the type string it's actually a string slice that we're creating but that's not accepted and so we can quickly rectify by gradient string and this will give me the opportunity to talk about another useful functionality of rust we just create another string we create a variable called name and we just do a string from bird similar to javascript typescript if the parameter you're trying to use is the same as the name of the field that you're trying to populate you can shorten everything and just pass in the name of the variable like so alternatively this is fine too now that we have a now that we have an instance of our bird struck we can just use it so we can just call bird dot nick name and then now we run the code we'll see that we'll print the name of the bird which is just bird which you see right here and that's basically structs in rust in a nutshell now that we know how to create structs or classes next question is how do we do object-orientated programming the interesting thing about rust is that rust actually does not support inheritance where you extend the class it only supports interfaces the rest how we handle interfaces is we use something called traits i'm just going to paste let's take a time so you define a trade by using the keyword trade and then you give it the name of the trade that you want for other classes to implement so a bird is an animal and so we'll say animal has two methods that we want to implement can't fly and is animal just like a normal interface you can create a function that has been implemented by the class that's extending it so in this instance we have cam fly the method signature doesn't take in any parameters it just has instance it just references itself and it returns a boolean we can also add a default implementation such as what we have with this animal same method signature and return type we can actually implement the method which returns true of course when we do extend it we can overwrite it to extend a trade all we need to do is use implement keyword again and just implement the trade animal for the bird struct and then if you read the error it'll probably say that we are missing implementation of can fly so all we need to do is implement it and we usually do that by pasting and we just return true and that's it for implementing our trait now to show everything works we can just do finland bird dot can fly and bird dot is animal then we run it we can see that we return true true for both and to be complete also override the is animal function first as you see i set example false so now we call the code again we'll get true false and that's everything you need to know about object-orientated programming with rust after structs we have enums so in most languages enums are just objects that represent a certain value that's the same case for rust however rust has been more interesting in that these enums can actually store additional values so i'm just going to place an example so here's the my enum type that i created syntax exactly the same you have a enum and then you give the name so there are three enum values that i've assigned to my enum it's a b and c a is just the value a by itself b interesting enough you actually store the value the integer inside of it and c is you can also store a struct like object so in this case c has the two fields x and y which are both integers and what you see up here is essentially an attribute that tells that tells the compiler how to print your enum which is going to be relevant because we'll be printing it soon as such so if you look inside our main function we are using our enums we have our variables a b and c to create a num you just call the enum class that you created and then you do double colon to reference the field and the field in this instance is a likewise if you want to instantiate a b type with a certain integer we just do colon colon b and then we give it the type and for our c type which we have a struct we do something very similar we do and c and then the over and close brackets and inside of that we just define our x and y value so we just do a quick print of these values you'll see that these are what our enum represents so one way to extract the value of our genome is to use if statements this isn't your typical if statement what you see right here is if let your enum tau and then the value equals c and what this really is saying is if our well not z bar b if our b type is a enum b val represents our variable that we stored and then we can just print it likewise if our c is a c enum then we access the fields of our c e num x and y and then we can just print it and then if we run cargo run again we see that we print out our new types our five that we stored in our 10 and 20 x and y value and so that's roughly enums on a high level next i want to talk about the standard library that's available in rest the first classic example is a vector or a dynamic array depending where you come from with languages like python and javascript arrays are already dynamic and you can increase and decrease it now to define a vector and just like any other statically typed languages you just define the parameter you want to and to create a vector there are a couple ways but the easiest way is we use the keyword vec with the destination mark which means we are using a macro that rust provides us and to create the vector we do the we can initialize it the same way we do with an array we can explicitly define the value in each index or we can even provide a range for example from zero to five so let's just do one two two four five a vector is pretty much the same as an array except that its size can be dynamically altered but as you see we still have some existing functions we still have our vector.lane we can get the value at whatever index we want to the major difference is that we can now add and remove elements so we can do something like vector.push and then this won't work exactly quite yet but we can push in the number six and this fails because we're trying to modify a unmutable object or a immutable object so we can easily rectify that by using adding the new keyword so this will push six and we can also use the remove function and maybe we can remove the first index which would be our one and then we just print our results run our code and we see that we have two three four five six we added the six to the n and we removed one from the list this is a basic introduction to a vector if you want to learn more about it check out the documentation another commonly used data structure next to the vector is the map so for those not familiar maps are basically objects that allows you to store data in a key value pairing you use the key in your map to associate a value to it so here's a quick code example just paste it a hash map in this instance unlike a vector you actually have to import from the standard library and so looking at the example let's create a variable map we make sure it's mutable and we just define the hashmap we call the hashmap object and then we call the new function to create an instance of a hashmap so operations for hashmap is pretty straightforward there's typically three things you have your insert your get and your remove in this instance our hashmap takes in a number as a key and then as the value we store a string slice then this code will print to show you what the value is to retrieve the value well it's actually it's pretty interesting unlike in other languages when you retrieve an object if you look at the definition of get you see that right here it returns a option type not the actual value that you're storing the options contains the value i'll quickly talk about option in another example but essentially in this instance option you can think of as a enum with two values it's either sum or none so basically a success type or a failure type it's similar to optionals in java if you've worked with it or potentially kind of like promises in javascript where something could be successful or you could have an error so in this instance we use the our match flow control or our kind of switch statement and we retrieve the value that's stored at the key 0. what's interesting in hashmap is that we actually don't want to pass in the value of the number we actually just want we always want to pass in the pointer to the value in our instance if we do get sum the value from sum is stored as a parameter we can call it anything i just call it string but this can be string one and it'll still be fine and so if we get something back from our get as in the key and value exists we just print out the value otherwise if we get done we just print that doesn't exist and to show an example i will also call get to find a key of two which doesn't exist and finally to remove a key value pair it's pretty straightforward we just call map.move and we just give the pointer to the number and i'll print it out to showcase that new cargo run you see that initially our map is zeros paired with high and one is a pair of high two and then when we print out the value at key zero we get high but when we try to print out the value associated with key two it doesn't exist because we divide it in and then if we remove the key value pair of zero we see that all that's left in our hash map is our one key and that's basically hash maps as usual there's a lot of other functionalities available that you can see in documentation but this is the high level we need to know to get a hash map next up is options we already talked about options when we try to retrieve a value from our map as you can see right here so to formalize everything here's another example a option essentially is a enum that has two types it has none which if consumed rest will automatically throw an exception and it also has a sum type which stores a value the value can be anything it's just something we put inside of it ourselves so in our example we have a function called divide divide takes in a dividend and a divisor and then we will return a option as you see right here a so in this function it's straightforward if our dividend mod or divisor is not zero that means that we cannot divide this number evenly we will just return the nun type otherwise we return the sum type and the value would be the number that we divide so now to quickly use this we will get rid of our implementation and i'll just paste some helper code we had beforehand so we have two pieces of code divide one divide two the five one we call we get the option from divide when we pass in four to be divided by two and for the phi two we do we get the option of two divided by three so there are a couple ways of extracting out the value the first way we already saw when we used the match statement to see to get the value the second way we can call a unwrap function on the code so unwrap will return the type that's expected of the option quickly run that we'll see that our object that we get divide 1 is a type sum2 and then once we unwrap it we get the value 2.
now the reason why i commented out us unwrapping our second option it's because if we unwrap a nun type it would throw a panic and a panic is rust version of a accession so with this code we if we do cargo run we would crash during our run time we'll get a runtime exception saying here that uh we panicked when we unwrapped a value that we unwrapped a option that has a done type there are some other interesting ways of unwrapping the value but this is options in a nutshell next step is results results are very similar to options instead of an option where we have a type or none we have a ok and a error type and the error type can be anything specifically a commuter i 32 or specifically in this case i'm going to use a enum called my error and it returns the error one type so specifically i'll just add a my error enum type to be a return value of our result the specific syntax that we see appear as an attribute essentially it's telling the compiler to figure out how to print out the error type of our enum when we try to print the message now to define our result type a result has two types are enum specifically an error and an okay an error is essentially you know that contains basically any error message it can be an integer it can be a string it can be your own custom type that you defined and there's also an okay type which contains the value that you return if it's successful so in our divide function we've previously just returned none when our number is not divisible however maybe we want to actually throw an error and so to do that we would just return error and then in our error type we just throw our enum in which is my error and then error 1.
and then for our success we just return a okay value with the whole number now we get to the interesting part of using the function the result type so here's some code so we call divide with 4 divided by two and we store that value inside of it we'll call divide one way of accessing the type safely is to just do a match statement and then see that if it's okay we just print out the divided value otherwise if we get an error we just print out the error which as you can see is this is this object so that's one way but potentially that could get really nested another option we could do is we could use an if statement and wrap our divide and check to see if our divide is okay and if it's okay we can safely unwrap the value of course we could just do what we did earlier and just directly unwrap it and that would work out fine if there's an error it would just print there otherwise we just print the value now some interesting application that you can use is this unwrap or function and what this does is it will unwrap the value that we store and divide so 4 divided by 2 is 2 and if somehow we turn an error instead we'll just print out 100 instead to showcase this i'll do 4 divided by 3 and you'll see that we print out 100.
that's one of the many ways of actually extracting out the value now another thing we could do is if there actually is an error you can use this expect function that i have up here and expect does is if it gets an error type then it will print a statement in this case we'll just print out the string b crash oh oh it's not the bottom two it's just divide now i run this again you see that we get an error saying that be crushed however if it is a valid value and we print it we can safely print out r2 as you can see right here if you stuck with this video up until this point congratulations i think you should have a relatively strong understanding of rest now at least hopefully more than you have when you started my hope is that this will help introduce you to rust instead of its syntax and how things work and give you the knowledge and information to dive deeper and learn more about rust however i think with some of the things that we talked about from defining variables to creating structures to using our standard library you now have a strong understanding we can now look into salon programs and understand what is roughly happening in the code if you found this video helpful please hit the like button subscribe in my next video i'll be going over a hello road salon program and start our adventure into developing a solana smart contract until then i'll catch you later
Up Next

How to Set Up a Solana Development Environment: A Beginner Tutorial
@brimigs
10.2K views•2025-06-09

Torrent File Format & Bencoding: A Technical Deep Dive
@AsliEngineering
12.5K views•2022-08-08

Solana Architecture: An In-Depth Explanation of Proof of History
@JoshsDevBox
18.8K views•2022-11-09

Understanding Ethereum: A Comprehensive Beginner's Overview
@99Bitcoins
3.1M views•2018-06-26
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Blockchain & Crypto





































