This comprehensive crash course covers Go programming fundamentals including packages and modules for code organization, primitive data types (integers, floats, booleans, complex numbers) and text handling (strings and runes), variables with multiple creation methods (var keyword, create-and-assign operator, compound assignments, block assignments), functions with parameters and return values, operators (arithmetic, relational, logical), control flow structures (if-else, switch, loops), and practical exercises including a dice roller project using the Go package registry.
Learn Go Programming: 2-Hour Beginner Crash Course Tutorial
Added:foreign go caught your attention but you're finding it a tad intimidating to learn or maybe you're a complete newbie looking to learn go from the grounds up well brace yourself my friends because you're about to start your journey of learning and mastering go and you couldn't have found a better resource for it now let me tell you why reason one you get to learn from Jason linen Jason is a world-class instructor who started as a self-top developer and then he transitioned into a university student this gives him a unique ability to understand the struggles of being self-taught but at the same time he comprehends how difficult it can be to understand complex subjects at a higher level needless to say he can relate to wherever you're starting from reason 2 Jason is a firm advocate of the practice makes perfect philosophy this means that you won't just be passively listening to lectures like some other YouTube courses instead you'll be thrown straight into the action with plenty of Hands-On exercises scattered throughout the crash course reason number three three your learning doesn't have to stop here this crash course is actually part of Jason's complete go programming bootcamp course so once you've finished this video make sure to check out his complete course where you'll learn many more advanced topics all the way to even being able to get hired as a go developer one last thing if you're liking this content and are finding it helpful please drop it a like it really helps us out and it shows us that you want us to keep delivering more great free content for you guys but enough chit chat for me let me hand it over to Jason so you can start your journey of learning go enjoy [Music] hello and welcome to the ztm go Lang course in this introduction I'll be talking about the go language why you would want to program and go and a little bit about the course itself so why would you want to program and go go is an in-demand language used by high profile companies such as Google it's simplistic and easy to understand by design it has built-in dependency management including a package registry similar to the JavaScript npm ecosystem it also has a familiar C style syntax so jumping in and learning go is really straightforward and easy to do a few technical features about the go programming language are that it has first class concurrency Primitives and this makes the language perfect for back-end programming such as making web servers the go language also has Type safety which is enforced by the compiler so you'll be able to write your code as if it's like C but then you'll get type checking as if you're writing c-sharp or Java this helps make programs much easier to write and tracks down lots of bugs go is a memory safe language so you'll never get any use after free bugs it accomplishes this by using garbage collection so there's no need for you to manage any memory go compiles down to machine code for very fast speeds so your programs will always run extremely quickly even though the language is garbage collected since everything is running at machine code speed the garbage collector overhead is very minimal here's a little bit about the course we have lectures demos and Hands-On coding exercises we'll be working with the go CLI which is used to manage your project and we'll be utilizing the go package ecosystem and its generated documentation since go is a lower level language we'll be covering Concepts such as pointers memory and concurrency if any of these are unfamiliar to you don't worry I'll be talking about them in enough detail to make you more comfortable with them that way you're able to fully utilize the go language in addition to the regular exercises we also have recap exercises which will cover an entire section this will help solidify your knowledge about the topics learned in that section and finally at the end of the course we'll be building a fully functional GUI desktop application thank you for watching this introduction and I hope you'll enjoy my course on the go programming language I'll see you in the next video [Music] thank you [Music] congratulations you've just been hired at Keiko Corp as a software engineer Keiko Corp is a Silicon Valley Tech Giant with multiple clusters of applications powering mobile and web services Keiko Corps Services have an increase in popularity and are in need of some Performance Tuning your boss Bruno this guy here with the perfect hair as tasked you with rewriting Kegel Corps services to be more efficient this is a big task Keiko Corp relies on these services for their core business so there is no room for failure but this is your first time optimizing applications how are you going to increase the efficiency of keco Corp Services don't worry we are going to be learning the go programming language which was designed to build efficient services over the next few weeks you'll learn how to program and go which will help you achieve the task that has been assigned to you Bruno is confident that he made the right hiring decision but he wants caco Corp Services optimized yesterday we better get to work [Music] in this video we'll be going over the installation of the go tool chain and visual studio code the first thing you'll do is open up a web browser and navigate to go.dev once the page loads click on the download link under featured downloads if you're on Windows click on the link for Microsoft Windows then click on save file save it wherever you like once the download completes open up the installer click on next click the check box and click next I'm using defaults so I just click next all the way through and then click install once the install completes click finish after clicking finish your go tool chain is ready to run next we'll be installing Visual Studio code and its extensions back in your web browser navigate to code.visualstudio.com click on the download for Windows link wait for a moment and then click on save file save it wherever you like once the download completes open it up you'll need to accept the agreement and click next I use defaults for everything so I just click next all the way through and then click on install once the installation is complete make sure the launch Visual Studio code button is checked and click on finish and it may take a moment to launch the first time once Visual Studio code loads we're going to click on the extensions button on the left we'll type in go and it should be the first results in our extensions and have several million downloads we'll then click on the install button after you click on the install button we'll need to open up a go file in order to finish the installation to do so we can go back to the getting started page and click on open folder and open up the course content materials that you've downloaded I saved mine into my documents so just navigate to it then click select folder and then open up any of the go files you'll have a pop-up that says install or install all just click on install all this installation process may take a lot of time as there are a lot of tools to download and install in order to get Visual Studio code set up for go programming once your installation finishes click on always update if you get a pop-up and you should see in your terminal that the tools have been successfully installed and you'll have a message that indicates you're ready to go once you see that message then everything is good to go and we can start the course [Music] in this video we'll be talking about packages and modules packages and modules will be encountered as soon as you start writing go code so it's important to have an understanding of how they work packages are goes way of organizing code programs are written as one or more packages and packages can be imported from the go package registry packages should be focused and perform a single thing some examples of good packages are argument parsing drawing graphics and handling HTTP requests for each one of these packages you would just want to do the single task that it was designed for if you needed to do something else you can just create a new package to use a package all we need to do is write the import keyword in our code followed by the name of the package within double quotes since packages are so commonly used in go we can batch import many packages at once by using the import keyword again followed by parentheses each line would be a package so we have the name package along with the namespace slash packaging package it's customary in go code to have a namespace and then your package name that way if you have multiple packages they'll all be listed under the same namespace by default whenever you import a package in go we have to refer to the name of the package in your code if you don't want to do this we can use a DOT before the package name and we'll be able to access all the functions and structures contained within without having to type in the name of the package we can also rename package Imports so for example on this second line here we have package name as the name of our package however that's kind of a long name so we can just refer to it as PK so in your code you'll just be typing PK instead of package name now let's talk about modules modules are simply a collection of packages they're created by having a go.mod file in the root directory of your project the go.mod file can be managed by the go CLI and it contains information about your project which includes dependencies the Go version and the package info all go projects have a go.mod file here's an example go.mod file we have the module keyword followed by the name of the module here we're using the namespace of example.com but you can use whatever you like so this module would be named practice and this is the namespace example.com we then have the Go version indicated here so we just type the word go and the current version that we're using or whichever one you use to compile the program next we have a require block and we're using parentheses just like we did with the Imports each one of these lines here in the require block is going to be a package along with the version that we're using within our code you can see here we have to use the entire namespace so we have github.com color would be the name of the package and this entire section is the namespace as previously mentioned the namespace can be anything you want it to be however it's customary to include the URL in the namespace that way people can easily find your code to recap packages are Go's way of organizing code packages should be a single program or single purpose Library packages can be published to and imported from the go package registry modules are just a collection of packages and they're declared by having a go.mod file and this file can be managed by the go CLI thank you [Music] in this video we'll be talking about data types including primitive types and type aliases so first let's cover exactly what a data type is all data in programs consists of binary numbers meaning zero or one a data type is just the way that the program can interpret the binary numbers letters and words are all different data types some examples of different data types are 15 the letter Y and the word hello go is aesthetically typed language so data types in a go must be provided by the programmer go uses a technique called type inference to determine what type of data it is working with this means that data types only need to be provided in specific circumstances and you can always specify the type if you want if you do specify the type and you end up using the rock one by accident you'll get a compiler error this is how the go compiler is able to provide type safety in go all primitive data types are numeric this means that they're simply a stream of bytes the type indicated in the code is simply a convention it is possible that the data is invalid for the given type but this only applies when you're working with user input or if you're manually manipulating the binary data itself so for the most part the type that's indicated in the code is the correct type let's cover a few different types that are available first we'll talk about signed integer types assigned integer is just a number that is an integer and it could be negative or positive and here's a listing of the available integer types that are in go along with the ranges we also have unsigned integer types unsigned integers are integers but they're positive only and they include zero and here's a listing of the ranges for unsigned integers at the bottom here we have the uint PTR which stands for unsigned integer pointer that will be the pointer size under current architecture what that means on 64-bit systems is the uint PTR type will be a un64 on 32-bit systems it'll be a un32 etc some other data types that are available are the float32 which is a 32-bit floating Point number floating Point numbers are just decimal points we also have float64 which is a decimal point number with enhanced accuracy we also have complex 64 and complex 128 which includes real and imaginary parts and then we have a Boolean which is simply true or false we can also make type aliases what a type Alias does is simply assign a new name to an existing type this is useful to provide an indication of what kind of data is being utilized down here we have some examples of type aliases we have the type keyword along with the name that we want to provide as a type Alias and then the original type would be the third part of the statement so here on the second line we're creating a new type Alias we're calling it Direction and we're assigning it the byte type for the third one we have the speed Alias and that's going to be a float64.
and you can have type aliases on top of type aliases so on this last one we create a new type Alias we name it velocity and we set it to be the type of speed and we know a speed is a float64 so here the velocity is actually a float64.
the primary reason for doing this is to make your code easier to read so instead of just having a function using float64 we can have the name velocity so we know exactly what we're working with we can also convert between different types using parentheses so here we have two type aliases one for user ID which is an integer and one name speed which is a float64. if we wanted to create a new user ID we just Supply the name of the type sub parentheses and then the underlying value that we can use since 5 is an integer we'll be able to create a user ID the same thing goes with speed we have the word speed parentheses and then we have a floating point value within the parentheses and that will create a new type of speed let's recap a data type is a way to specify how data should be interpreted by go go uses static typing which is checked at compile time the compiler uses a technique called type inference which automatically determines which type to use type aliases can be created to give new names to existing types and here we have an example of how to do it we use the type keyword followed by the name that we want along with the underlying type converting between types requires parentheses so if we want to convert an integer to a user ID we just have the name user ID parentheses and then we have the number five as our integer [Music] in this video I'll be discussing strings and runes including text encoding about runes and about strings first let's talk about text encoding textual data and go uses utf-8 encoding and encoding is a way to represent thousands of different symbols using Code pages code pages are tables which use the first few bytes of data to determine which page to use and each symbol on the code page is called a code point let's take a look at an example code page if we look at the lowercase D here we'll see that we're at code point one and three so to create a d it actually takes two bytes in this case we have to have a one and a three down here at the bottom if we want to create this Japanese character we'll have to use 4f followed by one so this particular character here takes three bytes four F and one in go when we work with strings and runes we're actually working with individual bytes not letters themselves so it's important to understand that letters can consume more than one byte now let's talk about runes text and go is represented using the Rune type this is similar to char in many other programming languages like C roon is just an alias for INT 32 which is just a 32-bit integer since runes are just an alias for n32 you're actually just working with numbers whenever you're working with a rune this includes when you try to print out messages using runes in order to print the actual character it represents you'll have to use a special formatting operation which we'll cover later runes can represent any symbol and this includes letters numbers and emoji let's take a look at how runes are represented in memory here we have two green rectangles which represent int 32s each one of these blocks are eight bits which adds up to 32 bits we have here on the bottom the number of bytes so here's the first byte second byte third byte and fourth byte of a 32-bit integer to represent the capital letter Q we have to have 51 in our position one byte to represent the zigzag we have to have this combination of bytes in these specific locations in order to get a zigzag the reason this is important is because the letter Q is only one byte the zigzag is three bytes but if we were to try to iterate over each letter we'll actually be iterating over each one of these bytes instead of the entire letter itself once we get to the section on looping we'll be covering how to iterate over the actual representations instead of the byte values now that we've covered runes let's take a look at strings a string is a data type for storing multiple runes and strings are just an array of bytes and a string length there is no null termination with a ghost string like you have in C when iterating a string iteration occurs over bytes and bytes are not symbols as we previously seen special iteration techniques are required to retrieve these runes and symbols which we'll be covering in a later lecture let's take a look at how strings are represented in memory on the left we have some runes we have a Bitcoin the number three a right arrow and a cent sign each one of these runes has a specific bit length on the right we have a string which is just a combination of all of these runes this particular string is nine bytes long we have three bytes from the Bitcoin one byte from the three three bytes from the arrow and two bytes from the cent sign so if we were to iterate through the string we'd be going one byte at a time and if you split these bytes in half then you won't have a Bitcoin anymore you'll have some different symbol recall that runes are just numbers and since a string is composed of runes a string is just more numbers put together let's take a look at how to create some runes so to create runes in code you surround the Rune that you want to make with single quotes so here we're creating a rune a rune R and Rune seven you'll see also that we can create an omega symbol a ruby symbol and a one-half symbol instead of using single quotes like we're using here we're using back ticks the back tick symbol is next to the number one on your keyboard and you'll need to use it whenever you're trying to type a symbol that isn't present on your keyboard so basically anything that's not a through z one through nine and zero and any of these symbols such as the at sign dollar sign percent sign those are all okay to use the single quotes however everything else you'll need to use backticks if you aren't sure if you need to use single quotes or back ticks you could just always use back ticks and you'll get the symbol that you're looking for there is one exception to this and that is escape symbols Escape symbols start with a backslash so backslash n will turn into a new line and we'll see here in the string shortly that they'll be highlighted in your editor so you'll know if you're working with an escape sequence to create strings we'll use double quotes so here we have amount is 22 Euros followed by an escape sequence which is backslash newline so this string will have a new line at the end we can also put a single letter within a string using double quotes so here we have the letter K and that's a string instead of a rune even though we could just make this a rune since it's a single letter since we want a string in this case we can use double quotes that's fine lastly we have the raw literal and a raw literal is surrounded by back ticks you'll want to use raw literals whenever you're working with strings that have single quotes in them or double quotes the reason you want to use these backticks is if you have double quotes within your string since the double quote is used to create strings if you want to include them in your string either have to escape them with a backslash or you can just use a raw literal I recommend using a raw literal so it's much easier to read the string without a bunch of backslashes one thing to take note with the raw literal is everything you type in here is going to come out as is that includes this escape sequence here notice how this one is highlighted in purple and this one is the same color as a string that's because when we type a raw literal it's going to type everything literally as you see it so we're going to get a backslash and an n in the output instead of a new line so here we have a new line because we're just using double quotes and here we have a backslash n because we're using raw literals it doesn't apply any processing to your string so it's just going to come out however you type it let's recap text and go is encoded using utf-8 the Rune type can represent any individual symbol and roon is just an alias for integer 32 and they are created using single quotes the string type contains a series of symbols as bytes strings are not null terminated and they are created using double quotes raw literals are created using backticks whenever you type something in a raw literal it'll come out exactly as tight together [Music] in this video I'll be discussing the go CLI tool along with a few of the common commands that we'll be using throughout the course the go tool chain provides the go command line utility this tool is used to update dependencies built-in test projects manage build artifacts and format source code so basically everything you need to do to work on a go project the go tool will help you out let's take a look at a few everyday go commands the first one is build build will build the project and emit an executable binary build is the command you'll want to use when you want to distribute your project the dice command is build dash race what that will do is check for concurrency problems so if you've written a concurrent program in go which is really common since it's so easy to do you'll always want to check your Source by using build dash race and it will emit any errors if it finds problems next up we have the Run command the Run command will just run the project directly without emitting an executable binary this is useful when you're testing code or when you're working through the exercises as part of the course the mod command manages your modules and dependencies specifically your mod.go file and the mod tidy command will clean up that file if there's any errors and download and update any dependencies that your project relies on next we have the test command which runs the project test Suite it's always a good idea to write tests for your code that way you can ensure that it maintains the proper logic after updating it lastly we have the format command short fmt for short that formats all your source code files and usually this will be automated with your IDE but you can always run it manually if you so desire [Music] in this video I'll be talking about variables I'll be discussing what variables are how to create them the comma OK idiom and naming and constants so let's talk about what variables are first variables provide a way to store and access data in your program the data within a variable can be anything or and it can vary which is where it gets the name variable variables are simply an alias to some data in memory and it makes it easier to access that data when you store data into a variable it's called assignment so you'll be assigning data into variables variables have multiple components we have the name of the variable the data that's part of the variable or lack thereof and a data type there's multiple ways to create variables and in this example we'll just be creating a single variable so we'll use the VAR keyword to create a variable we'll give it a name this one is named example we'll use the equal symbol to assign a value and in this example we're assigning three so the number three will be assigned to the example variable we can also use type annotations as in this example so we're creating the same variable that we're giving it the int data type and again we're assigning it at three in this second example since we're using a type annotation of integer if we try to assign a string such as hi then we'll get a compiler error because high is a string and it's not an integer in this third one we're creating a variable named example and we're setting the data type to int however we're not assigning any value initially so this will be considered an uninitialized variable and it'll get a default value if we fail to assign to it in this case we are assigned to it so in the second line we have example equals three so we're assigning 3 to the example variable and again if you forget this line then this will be equal to zero which is the default for an integer we can also create multiple variables at the same time so here we're creating variables a b and c and they're separated by commas we have our assignment equal sign then we're assigning these to 1 2 and the string sample so a will be a one B will be a two and c will have the string sample this way of creating variables makes it really simple to assign multiple different data types to multiple variables we can also create multiple variables using a block so if we have the VAR keyword and parentheses everything within this block will be created as a variable so we'll create an a it'll be an integer and we'll set it to one we'll create the variable B also an integer we'll set it to two we'll create the variable C and assign it to sample we didn't include a type annotation here and that's because the compiler uses type inference so we'll see that we're working with a string because we have double quotes and it will assign a string type to C down here after this block we'll be able to use a b and c as individual variables as if we had created them one line at a time we also have a create and assign shortcut this is done by having the name of the variable and then we have a colon equals and then the value so this is what you'll commonly see in go code because it's shorter and easier to write and you get type inference as well so this example variable will have the value 3 assigned to it because we're using the create and assign operator we can use the create and assign operator with multiple variables as well so we have a and b a will be 1 and B will be the string sample here's a little bit more information about variables variables can be reassigned and assigned to other variables so here we're creating variable a and we're assigning it the value of one later on in the program we can then reassign 2 to the value of a then we can also assign 3 to the value of a remember that this is the create and assign and since a has been created right here we no longer need to create it again down here so we can just use equal to assignment over here on the right we have a equal to one we then create a new variable B and we assign it to the value of a so B will be 1 because 1 is inside a and since 1 is in a one will not be in b and we can also use the VAR keyword to create the variable C and just assign it to B which will also be one whenever you do this we're creating a copy so even though we have an A if we were to change later this a into a 2 for example B will still be equal to 1 because we just copied the data that was in a we created this variable it's just a copy of a we're putting that copy into B the same thing goes for C down here so when we do create a new variable C and assign it to a copy of B variable names can only be used once per scope what this means is here we're creating a variable a assign it to the value of one later on we try to create variable a again using the VAR keyword and assign it to five this won't work so that's going to be a compiler error because it's already been created one time in this case we need to just drop the VAR keyword and have a equal to 5.
variables that are declared but not assigned will automatically have a default value so whenever you create a variable such as this name variable as a string it's going to have a default value because we haven't assigned anything yet so there's no equal here so we have no value what this means is we'll get a default and so for string the default is an empty string so you'll just have it's the same as doing double quotes there'll be no bytes within the string and it'll just be empty or numbers the default is 0 and for everything else the default is nil nil is equivalent to null in other programming languages meaning there's an absence of a value so there's no value whenever we have a nil value we also have the comma OK idiom which is a special case that allows us to reuse create and assign operators so as we saw earlier we have an A we're creating and assigning one we then try to create a again and assign it to five so this will be an error because we already created a one time so we can't create it again in the middle here we have a comma B so we're creating two variables create and assign we'll sign one to a and we'll assign 2 to B later on in the program we can do c comma B create and assign and we'll assign 3 to C and then 4 to B even though we created B right here since we're using the comma OK idiom we're allowed to reassign B again even though we have the create and assign operator so the reason we have this special case is because lots of code might give you errors and when that happens we'll have the variable assign and possible error values and we'll need to check for those errors which we'll be doing later but we'll use the create and assign it allows us to easily create this new variable while still reusing our error values if we weren't allowed to do this we'd have to have like Air 1 Air 2 air 3 and it's much easier to keep reusing the same error variable so it's going to contain the same type of information which is just error information naming variables in go has a convention and we use camel case camel case always starts with a lowercase letter and each word has an uppercase letter to denote where the word begins so we have my long variable name so the l v and N are all capitalized and the m is lowercase whenever you're coming up with variable names it's good to have something that's descriptive for what's going on so here's an example of a good variable name we have total guests is equal to 12. and here's a bad one and we have TTL which is equal to 12. so TTL might be short for total or time to live and even if it is total we still don't know what the total is about so to make your code easier to follow it's always good to use descriptive variable names also these are code comments so double slashes is a code comment which are ignored by the compiler and just allow you to leave notes for yourself and other Developers we also have constants which are created using the const keyword they're useful when you're declaring some value that needs to be utilized throughout some or all of the program and in contrast to variables consonants never change so once you assign them you cannot reassign them here's some examples of some constants we have a max speed set to 30. we have minimum purchase price set to 750 and we have application author is equal to Bob notice that we don't need to use a colon here we can just assign it directly and the naming convention for constants is a capital letter for each word so in C usually these would be all caps but in go we prefer to just start with a capital letter let's recap variables are a way to access memory locations using an alias there are multiple ways to create variables we can create variables on their own we can make compound assignments we can create variables using blocks there's also the create and assign operator variables can be assigned to other variables and variable names can only be used once per scope this means once you create a variable you're unable to create another variable of the same name variables that are declared but not assigned to will have a default value and the default value for numbers is zero and for Strings is just an empty string the comma OK idiom allows you to reuse the second variable when you're creating a compound variable assignment and comma OK is frequently used when you're checking for errors [Music] in this demo we'll be creating and utilizing variables in a simple program once you're ready fire up visual studio code and let's go once Visual Studio code loads you'll see the getting started screen we can then click on open folder to continue if you don't have the getting started screen we can click on these documents right here to open the Explorer if we click on that we'll see what the Explorer has loaded and then we can click on open folder from here once you click on open folder you have a file browser and you're going to navigate to the location where you downloaded the go Lang files so you're looking for the zero to mastery.io dash golang folder I'm going to double click that and we want the SRC directory here and then finally we want to double click on the lectures folder right there once you double click on that click on OK or your equivalent on your operating system to open up the folder once it loads you'll see that we have the lectures at the top followed by a demo folder and an exercise folder and finally a go.mod file it's important that you have the correct folder open that way the go Tools in Visual Studio code will work properly and you'll be able to easily run the programs just like I do in the demos if you see down in the bottom right where it says analysis tool is missing if you have that message just click on it then click on install and you have to wait for a moment for the tools to be installed once that's done we can close this and as long as you're in the correct folder here and you don't have any error messages down here then you're ready to go so we'll go ahead and close this getting started page we'll click on the demo folder we're working with variables so we'll scroll down to the variables folder and double click on the variables.go file you'll see that all these here are red and that's because all these files are empty and they're just templates that we're going to be using during the demos we won't be trying to compile every single one at the same time we're just going to do these one at a time so you should have no problems writing the code I'll be closing these windows that way there's a little bit more space to work with all right so the first thing you'll notice we have the package keyword here and the word main so what that does is that specifies that we have a main package and allows us to have the funk Main and the main function is the first function that's ran whenever we have run a go program for most of the demos we'll be utilizing the main package along with the main function to implement and test out different code you'll also see that we're importing the fmt package fmt is the format package that's part of the standard library and it's used to print out information so we're going to be printing out information and creating variables in this program so the first thing we'll do is we'll just create a string variable so we'll use the VAR keyword and this will be called my name and we'll just place your name here my name is Jason so I'll just put Jason there we'll then print it out so we can use format Dot println and that's short for print line and all we need to do is have a string so we'll use double quotes and we'll say my name is and then we'll have a comma and we'll have the my name variable so what's going to happen here is we're creating the my name variable it's going to substitute Json for here my name and we can now print out some data with the print line function we're going to print out my name is and then it's going to print Json because the my name variable refers to Json we're not going to save this and run it so to save you could just do Ctrl s and we need to run it in a terminal so to do so we'll open up the menu go to terminal and click on new terminal once your terminal loads we can type in go run we'll use a DOT slash demo slash variables that's because we're on the variables lecture and the variables program once we hit enter it should compile and run the program and here we have the output my name is Jason which is just what we expected we have my name is Jason the print line function will automatically add a space whenever you have a comma so if you add additional variables here so if we just copy this again we'll have my name comma my name and so now it'll just print out my name twice with a space in between I'll be switching to an external terminal from now on but you can continue to use the integrated terminal if it's easier for you the next thing we'll do is create another variable and we're going to be using type annotations so let's have the variable be named name we'll set the type to be a string and we'll assign this to the name of Kathy we can then print it out name equals name so just like before we have name equals and now it's going to print out the name which is Kathy so here we're just using type annotations next thing we can do is assign and create or create an assign rather so we have username equals admin we're using Create and assign with a colon equals again we're just going to print that out username equals and then we'll have username if we check to see what we've got so far we should have my name is and then your name name equals Cathy and then username equals admin so I'm going to run this and we'll make sure that's what we get and there we go we have my name is Jason Jason because we put it twice name equals Kathy and username equals admin the next thing we're going to do is create an uninitialized variable so we have a variable name sum and we're going to assign it to be some type of ins and we didn't assign any value and we're just going to print it out so we have the sum is and then we'll use that variable and this is going to be assign a default value of a zero since it's an integer so when this prints it'll say the sum is zero now we're going to make a compound assignment we have part one and other create and assign one and five we're going to print this one out part one is then we'll have part one another comma other is and we'll have other so just like the other ones we have two variables part one other and we're just printing everything out using commas and the print line function so it'll print out part one is one other is five next we'll be utilizing the OK error idiom so we'll have part two other and we'll assign this to two and zero we'll then print this out so we'll have part two is part two other is other so you'll see we don't have any red squigglies here that's because when we have two variable assignments here we can reuse this second one so other is being used twice so when this one prints out down here it'll be a zero now when this one prints out it'll be a five next up we're going to reassign a variable that we already created so we created the sum variable up here and now we're going to assign a value to it so we'll make sum equal to part one plus part two which should be equal to three because part one is one and part two is two we'll then print that out sum equals and then we'll have the sum next we'll create a block assignment so we'll use the VAR keyword followed by parentheses and we'll create two variables and we'll be lesson name and we'll use variables and the other will be a lesson type and this lesson type is a demo so we'll put demo here we'll then print both of these out and we'll print out the lesson type as well the last thing we'll do is we'll have a compound assignment where we ignore one of the variables so we'll have word one word two and an underscore we'll create an assign and we'll assign to hello world and an exclamation point we'll then just print out word one and word two so word one is going to contain hello word two is going to contain world and when we do a print line hello worlds will be printed we won't have any exclamation point because we're ignoring that using the underscore so this exclamation point that's just going to get thrown away if we go to our terminal and run the program we should get all this information printed out and there we go so here we have the sum is zero so that's the uninitialized zero we then have part one is one part two is two and we have the sum of these two as three so we reassigned sum to be the value of three here's our two variables that we created in a block assignment and finally here's our compound assignment at the end where we ignore the exclamation point go has many ways to create and assign variables you'll see all of these used when you're reading other people's go code so it's good to become accustomed with all the different ways that it can be done this includes the demo on working with variables I'll see you in the next presentation [Music] in this coding exercise we'll be going Hands-On with variables once you're ready fire up visual studio code and let's go once Visual Studio code loads we're going to click on the exercise folder we're doing variables for this exercise so we'll click on the variables folder and then double click on variables dot go the coding exercises in this course are designed to be done on your own after watching the lectures and following along with the demos there is a summary of each exercise describing what you will need to make a list of requirements to be followed and some notes to help you out you should always give the exercise a go before watching the video once you complete the exercise continue on with the video in order to see the solution which may differ from your own seeing alternative ways to implement the exercise will help round out your go knowledge which helps you become more proficient with the language go ahead and start working on this exercise now with the video paused and once completed resume the video to see my implementation alright let's go so in this exercise we'll be printing some basic information to the terminal using a different variable creation techniques so the first thing that I usually do when I have something with a list requirements is I copy and paste them down into the source code area that way I can easily just fill out the information so I'll paste those in now so the first thing we need to do is store the favorite color in a variable using the VAR keyword so my favorite color is red so I'll do a favorite color equals red I'm going to print it out my favorite color is and we have the favorite color variable next we need to store the birth year and age and years using two variables and compound assignment so we have birth here age in years and I was born in 1987 and that would make me 34 years old today I'll then print these out born in birth year aged age and years we now need to store my first of last initials and two variables using block assignment so we'll create a new block so first initial that will be J I'll use runes for this one and my last initial will be l again we'll just print them out next we need to declare but not assign a variable for your age in days then assign it on the next line by multiplying 365 with the age variable created earlier so we'll create a new variable age and days and we'll create make that an integer we'll then assign agent days equals 365 times the one we created earlier which is up here age and years and contains the value of 34.
so that'll be age in years and then we'll print that out as well I am age in days old now that it looks like I'm done I'm going to hop into a terminal and give it a go so I'll run this with go run dot slash exercise slash variables and so we have my favorite color is red I was born in 1987 aged 34 years my initials are 74.76 so this happened because I used runes and runes are just numbers so I'm going to go back and change those to Strings so we go back up here we can just change this to double quotes we'll use strings for now later on we'll learn how to print runes using special characters that allow us to print it with the actual glyph value instead of the numeric value but for now we can just use a string so let's try that again so my initials are J L and I'm 12 400 Days and 10 days old this concludes the exercise on variables I'll see you in the next presentation [Music] in this video I'll be talking about functions I'll explain what functions are how to create and use functions and how they work here's a little bit about functions they're the most basic building block of go programs they allow functionality to be isolated which makes programs easier to test debug extend modify read write and document functions are simple they take data as input and they return data as output note that the input and output portions of functions are optional so you can have a function which takes no input and a function that returns no output an example of this would just be displaying a generic message there would be no input of the function and the function will return no value let's take a look at how to create a function we'll use the funk keyword followed by the name of the function we then have parentheses and within the parentheses we have a parameter after the parameter we have the type of that particular parameter if we want multiple parameters we can separate them with a comma so in this function we have parameter one and parameter two and as you can see those will be our input datas and it must be of the type specified here the output data is listed here as a specific type and it's outside of the parentheses we then have curly braces and within those curly braces is the body of the function the body of the function will have all the code for processing the information so within this function body we can access param one and param two param one will be of this type param 2 will be of this type and within the function body we must return whatever this type happens to be here's an example function we have the funk keyword and we're naming this function sum so we're going to be adding things together we then have a LHS and rhs let's just sort for left hand side and right hand side we use a comma to separate the two parameters and we're assigning both of them to an integer value so if you have multiple parameters and they're all the same type you can just list them with commas at the very end indicate which type you'll be using the return type for this function is integer data and within our function body we use the returned keyword to return data from the function it's in the function we take the left hand side and we add to the right hand side and then we'll just take this together and return it as an integer when we use functions it is referred to as calling functions the color of the function provides arguments to be utilized by the function parameters arguments are the input data to the function so here's our sum function that we just wrote earlier and we have a create and assign variable here using the create and assign operator and we're creating and assigning the value of this function so we're going to call the sum function with arguments 2 and 2. this 2 will go into the left hand side and this two will go into the right hand side we'll then enter the function body we'll return the result of the left hand side plus the right hand side which will be 4.
gotta get returned as an integer and that 4 will then be placed right here and then eventually we'll have a 4 in result so we're creating a variable and assigning it to the value of this function call which will be for we can also return multiple values from functions so here we have a function named multi-return and it doesn't have any function parameters it's going to return three integers and so we have multiple return values by using parentheses followed by the name of each type that we want to return within this function we're returning 1 2 and 3. we can create variables from each one of these return values by using commas so we have an a comma B comma underscore and we're creating and assigning those variables to the return values of the multi-return function so a will be one from right here B will be 2 right here and whenever you have an underscore you're ignoring that return value so we have a three but we're going to ignore it so maybe in this particular case the programmer wants to ignore the third value the naming convention for functions in go is camel case so just like variable names so we have the lowercase M to start the function name and each word will have an uppercase letter just like variables we'll want to use names that convey the purpose of the function so here we have a good function name the function name is encode and we're going to encode some data which is a stream using the supplied codec there here's a bad name for a function it's just named compute we're Computing a b and c they're all 64-bit floating Point numbers and it returns a floating Point 64-bit number we don't know what compute actually does it could do any kind of computation it could do nothing we just don't know so this is not a very good name for a function we want a name that conveys what's actually happening and this will help a lot later when you go to read code and make modifications let's recap functions encapsulate program functionality which leads to more maintainable code functions have parameters which Define the type of input data functions are used by calling the function and supplying arguments to the parameters functions can return multiple values and an underscore can be used to ignore a return value if you need to [Music] in this demo we'll be creating and utilizing some functions once you're ready fire up visual studio code and let's go once Visual Studio code loads navigate to your demo folder or on the functions demo so click on the functions folder here and then finally double-click on functions.go once that's loaded you're ready to go so the first function we'll be creating is a function that doubles a number so we'll call it double and it's going to take a single parameter and it's going to be an integer parameter and it's going to also return an integer we're just going to return the number plus itself that way we can double it we'll then create a second function named add and that we're going to be adding two numbers together so we have a left hand side a right hand side and both are going to be integers since we're using the same type integer for both left hand side and right hand side we don't need to specify it two times so we can just use a comma and use int once and both of these here will be integers the add function is going to be returning an integer so let's return left hand side plus right hand side next we'll make a function called greet and that's going to display a message this function has no input parameters and no output data so we can just use parentheses with nothing in it and we'll just use a blank space right there in our great function we'll use the format package and we'll do a print line hello from greet function we go down on our main function we can start utilizing these functions we just created so the first function we'll use is the read function to call the function all we need to do is type the name of the function and our two parentheses the next function we'll use is the double function so I'm going to create and assign a variable named Dozen and we're going to take the double function we'll double the number six and that'll give us 12 which is a dozen only to print out this result that way we can see that we get the correct number next up we'll create a Baker's Dozen so a Baker's Dozen is 13.
so we'll use the add function and we're going to add our dozen that we already have We'll add one to it and we'll print that out as well so what we're doing here with the add function is we're adding the value of dozen and one here in our double function we're doubling 6 which is 12. that'll get placed into dozen so we're then going to add the Dozen from here that's going to be 12. and we'll add 1 to it and it's going to place 13 into Baker's Dozen so Baker's Dozen will have 13.
and finally we're going to have both functions call at the same time so we'll do another baker's dozen and that will be the result of ADD and double and then we'll print that out so here we're nesting functions we have the add function and the double function this double function is going to be called First and we'll get a 12 back once we have that 12 we'll take the 12 and the 1. add them together in this function and then return a 13 into another Baker's Dozen variable once you have all that in let's save our work and go hop into a terminal and see if we get the right answers to run this demo we'll use go run dot slash demo slash functions and so here we have hello from read function a dozen is 12. a baker's dozen is 13 and another Baker's Dozen is also 13.
this concludes the demo on writing and utilizing functions I'll see you in the next presentation [Music] in this coding exercise we're going to be working with functions once you're ready pirate Visual Studio code and let's go once Visual Studio code loads navigate to your exercise directory we're working with functions so click on the functions folder and then double click on functions.go as always with the coding exercises give it a go on your own first with the video paused then once completed resume the video for my implementation that way you can see alternative solutions to the problem all right let's go so in this exercise we're going to be working with functions and utilizing them in different ways the first thing I'll do is copy the requirements down to the coding area so since we're writing functions we can do them in any order we like so I'm going to start with this one down here so we're at a function that returns any two numbers so I'll just call it two twos so I can return eight two numbers that we want we need to return two separate numbers so our return value is going to be in parentheses and then we have two integer values that way we can return two numbers so I'm just going to return two twos next we can write a function that returns any number so in this function I'll just name it five and we'll return an integer and we'll return 5.
next we'll do this requirement so we need to write a function to add three numbers together supplied as arguments and return the answer so I'll call this function add three so we'll have an A B and C since we're working with all numbers we can just use integer right there and all three of these will be integers we are going to return an integer since we have to add them together and then we're just going to return a plus b plus c next we need to write a function that accepts a person's name as a function parameter and displays a greeting to that person so I'll name this function great person we'll have a name and that's going to be a string since names are going to be strings because they're consists of letters and numbers we're then going to use the format package and just do a print line I'll say hello name next we need to write a function that returns any message and call it from within format.printline so what this means is we're not going to be able to use the print line function within this one so we have to return the data itself and then it'll get printed later so we'll call this one hi there it could be any method we want so mine's just going to say hi there it's going to return a string so the string is the type that we want to return since we're working with messages and we're just going to return hi there in our main function we can start utilizing the functions that we created so the first thing I'll do is create person and we'll have this person be named Alice the next thing we'll do is format.printline our hither function so this fulfills the requirement up here or we need to write a function that returns any message and call it from within format.printline so we're calling our hi there function within format.printline so hi there is going to go here we're going to return a string and the I there will be placed into the print line function and print out on the terminal we then need to add three numbers together using any combination of the existing functions so I'm going to do a and b and we'll get our two twos that we created earlier and I'm going to have the answer and we'll add 3.
so we'll have the five function and our a and our B so we're going to add our 2 2 and 5 together so we should get 9 as our answer so our answer should be 9.
and finally we need to print the results so we'll just use format Dot printline and we'll print out the answer so I'm going to go ahead and run this and we'll see if we get all the things that I hope we get we'll run this exercise using gorun dot slash exercise slash functions and so we have hello Alice which is our name that we supplied we have hi there which is just the greeting that's within the print line and we have nine which are all the functions returning numbers and added together this concludes the exercise on working with functions I'll see you with the next presentation [Music] in this video I'll be talking about operators I'll be discussing what operators are going over arithmetic operators and logical and relational operators operators are used to perform calculations and comparisons here's some examples we have a lesson operator and we have a subtraction operator operators work on operands here we have an example we have the plus operator and it's operating on the operands A and B here's a listing of the arithmetic operators that are available within go we have addition which is plus subtraction as a minus multiplication is a star division is a forward slash and remainder division is a percent symbol you'll see on the right here we have the operators and an equal sign and what that does is it takes an existing variable performs this operation and reassigns the result to that variable so you'll see that a lot in code that you can use that to increment numbers or add some value to an existing variable let's take a look at how to use some operators so for using arithmetic operators here we're creating a variable named total and we're just using three plus three so our operator here is plus our operands are three and three and that'll be assigned to six and it'll be placed into the total variable to use arithmetic assignment here we're creating variable a setting it to the value of one we're using plus equals with three and so that will take the existing a and add 3 to it and then a will now be equal to four and that's the same as doing a equals a plus three so this is a shortcut for doing that we also have increment and decrement operators so these are very common in Loops here we have a variable I and we do plus plus we're just going to be adding one to the I and if we do minus minus we're going to be subtracting 1 from the I whenever you're working with arithmetic operators it's always going to be returning a number so you're not going to get any errors or any strings back you're always going to get a number that you're working with let's take a look at the relational operators we have less than less than or equal to greater than greater than or equal to equal to and finally not equal to relational operators always return a Boolean so whenever you're using in this example greater than and also equal to you're always going to get either true or false back so in this case if a is bigger than b because we're doing greater than then then that would be true and if x was equal to Y that would also be true and the x is equal to Y case if they're not equal then you're going to get a false and in the a greater than b if a is for example 0 and B is 2 then you're going to get a false back on that one now we'll take a look at some logic operators we have and which is two ampersands or which is two bars the bars are above the enter key below the backspace on most keyboards and we also have not which is an exclamation point and that'll invert a value so let's take a look at how to use those so what you can do with the logic operators is combined true and false things so in this example we have these would all be booleans so we have authorized and authenticated so both of these need to be true because we're using two ampersands so if both of those are true then the return value will also be true if either one of these is false then the return value will be false here we're using or with the two bars so if we have red or blue if either one of these is true so if red is true and blue is false we're still going to get a true back and that's because we're using or so we only need one of these things and there could be a there could be many you can keep going with as many as you want if any one of those is true then you're going to get a true back and with the exclamation point you're going to invert whatever you have so if heavy is true once you apply the exclamation point it's now going to be false let's recap operators operate on upper ends arithmetic operators enable calculations arithmetic assignment can calculate and assign to a variable in a single statement relational operators enable comparisons and logic operators enable combinations and negation [Music] in this video we'll be taking a look at if else I'll be discussing flow control using IF else with operators and statement initialization so first we need to talk about flow control program code executes line by line and flow control is a way to interrupt this line-by-line process we can have different lines of code that can be executed based on different conditions and these conditions are programmer defined and you can make as many conditions as you need in order to get your program to run and the job completed so this is what an if and an if else looks like we have the if keyword and then some kind of condition the condition must evaluate to either true or false if it's true code will be executed inside this block and so you can do whatever you want in here here we have an if else so same as above we have if some condition we'll do some code here if that's true if it's false else then we'll do something else in here so the first block is the true's condition and the else block is the false condition let's take a look at an example here we have if some username which will be a string if it's not equal to a blank input so there is a name then we'll process it and if the if the input is blank then we'll display some kind of error message and on the bottom we're just doing something similar without the else block so we only are interested in processing the username and we don't do anything else on the bottom example it's also possible to Nest else ifs so what we're doing here is we're checking someone's age so this entire thing here is going to evaluate to either true or false remember that relational operators determine true or false so if somebody's age is greater than or equal to 21 if that's true then we'll permit their entry to a venue if this is false we're going to go down to the next block here so else we use the keyword if again so else if we have parental approval and if that happens to be true then we'll permit entry again so if that's true that'll be executed if this one is false and this one is false then finally this last block will get executed and we'll have a some kind of code where they cannot enter the venue you can have as many else if blocks as you want for whatever conditions you're trying to test for so you can have one you could have none you can have five or six you can have 20. all of that's okay now let's take a look at how we can use if with some logical operators here we have if has ticket and ticket valid so this has to be true and this has to be true then we'll execute the code here in this block in this example here we have if the funds are greater than the cost so this whole thing will evaluate either true or false and the account is active so if that's true and this is true then we'll enter into this block here in this third example if we're either using a debit card or using a credit card then we'll enter this block since we're using or either one of these can be false so if this is false that's okay and if this is true we'll still enter if both of these are false then we won't execute the code here so if as long as one thing is true with all of these Expressions then we'll be able to use the if block here and finally here at the bottom we have a negation so if the quiz is not complete then we're going to display an incomplete submission warning this quiz complete here that's going to be a Boolean so that's either going to be true or false we can also use if statements with functions so here we have our if keyword and we're calling the temperature function of the freezer so we're checking the temperature on a freezer and if that temperature is greater than zero we'll display an alert and we can use multiple functions here so if the temp in the freezer is greater than the preferred temp in the freezer then we can display an alert as well and just like with the previous slides you can use or an and to combine multiple different function calls go has a feature called statement initialization and what this allows us to do is allows us to create a variable and do a comparison at the same time so here in this first example we're creating the variable named I using the create and assign operator and we're assign it to the value of 5. we then have a semicolon and we can do a logic check so here we're creating I assign it to five we then check to see if I is less than 10. if this evaluates to true then the block will be executed if this evaluates to false then we'll go down into the else block and do something else in this second example we're using the rank keyword and we're getting the user rank function and this rank function will determine if they're an admin or user or guest if rank happens to be admin then we'll be able to do administrative things here if the rank is manager then they can do manager things and finally at the bottom we'll display an error message because for this particular functionality they're not able to do anything unless they're an admin or a manager remember with statement initialization we need to have the if keyword followed by our initialization statement a semicolon and then our comparison at the end the comparison should always refer to the variable that you created in the initialization statement when you do so you'll be able to access this variable within this block something closely related to control flow is an early return an early return is simply using the if statement to validate some data when the data is validated you're able to continue with the function if the data fails validation you return early from the function you want to do this because it maximizes performance and once you've checked all the data you're able to use it without having any issues this leads to cleaner code and reduces the amount of bugs that you have in your program let's take a look at an example here we have a get session function and it returns a session token or an error the first thing we want to do is use if to check the error so if the error is not nil remember that nil is nothing so if it's not nothing meaning we do have some kind of error then we'll return immediately out of the function that's because this token will not be valid because some kind of error occurred the same thing down here with get card so here we use our existing token and our get cart function and if that's successful then we get a cart however if we have an error we need to check that and if we get an error back then we should return from the function if both of the error from get session and get cart if both of those are nil it will end up down here at the bottom and we'll have a valid token data and a valid cart data this makes it okay to process a shopping cart this if error is not equal to nil we'll see that a lot in your go code because when functions return an error you always need to check to see if that error value exists and if it does you want to return from the function and you can also perform logging in here if you like let's recap flow control is a way to change which lines of code execute if else can be used to conditionally execute code and we can also use else if for testing multiple different conditions if statements can be used with return values from function calls and logical inequality operators can also be used with if statements statement initialization allows for a variable to be created and tested within the scope of an if else block and early returns should always be used when possible for efficiency and code clarity [Music] in this demo we'll be creating a program that utilizes if else statements once you're ready fire up visual studio code and let's go once Visual Studio code loads click on your demo directory and we're doing if else so click on if else and then finally double click on if else.go so we have some existing functionality here and we're going to be utilizing it within our program so the first thing we'll do is create some quiz scores so we'll have quiz 1 Quiz 2 and quiz 3.
now we'll set those scores to 9 7 and 8.
next we're going to create an if statement so we'll have if quiz 1 is greater than quiz 2.
we'll put on a message we'll then continue with an else if so if quiz 1 is less than Quiz 2 open a different message finally we'll have an else keyword and then the last message will be the scores are equal so this first check checks to see if quiz 1 is greater than Quiz 2 the next one is quiz 1 less than Quiz 2 and the last one will cover any other cases since we have already covered greater than and less than the last case we'll be checking to see if it is equal to next we'll do we'll call our average function so if the average of quiz 1 Quiz 2 and Quiz 3 is greater than 7 then we'll put on a message and if it's not greater than 7 we'll print out a different message when we run this program we should get the output here so quiz 1 scored higher than Quiz 2 because quiz 1 is greater than quiz 2. and we should get here acceptable grades printed out for the average because the average of these is going to be higher than 7.
let's hop into a terminal and give it a go we'll run this one with gorun DOT slash demo slash if Dash else and so there we go we have quiz 1 scored higher than Quiz 2 and we have acceptable grades this concludes the demo on if else I'll see you in the next presentation [Music] thank you in this coding exercise you'll be creating a program that utilizes if else once you're ready fire up visual studio code and let's go once Visual Studio code loads navigate to your exercise directory we are working on if else so click on if else finally double click on if else.go to load the exercise file as always with the coding exercises give it a go on your own first with a video paused then once completed resume the video for my implementation that way you can see an alternative solution to the problem all right let's go so in this program we're going to be restricting access based on the day of the week and what kind of role a user has I'm going to copy these requirements and we'll paste it into our main function you'll see that we have some existing data so we have some variables created here some roles created here but we also have a few functions available we're going to be using all of this pre-existing program data within our own program so we don't need to modify any of the existing code we're only going to be focusing here on the main function so if we hop down into Main and we paste in the requirements we can start working on the program so the first thing we'll take care of is the admin and manager because they can access anytime so we'll have the role we'll check to see if it's admin or if the role is a manager then we'll use the access granted function next up we have contractors so contractors can access only on weekends so we need some way to determine whether or not it's a weekend first before we do this check so let's write a function to make that determination if we scroll up here on the days of the week we can see that they're numbers so we'll create a function and I'll just call it weekday and this will return whether or not it's a weekday so we'll take the day which is an integer so all these are integers so we see that there's zero through six Monday through Sunday and so our function down here requires an integer it's going to return a Boolean and that will just determine whether or not we're on a weekday so we could just directly return a comparison so if the day is less than or equal to four we'll just return that so we can see that Friday is four and everything less than 4 is also a weekday so if we just return whether or not the input day is less than or equal to four we'll know whether or not it's a weekday and if we want weekends we can just use an exclamation point to invert whatever answer we get back down on our main function we can do our if check so we'll do an else if so if the role is a contractor and it's not a weekday then we can grab them access next up we have members and members can access on weekdays so if the role is a member and it is a weekday then they're gonna get access finally for guests we'll use a role equals guest and if the day is Monday Wednesday and Friday so if the day is Monday or Wednesday or Friday then we'll give them access and everybody else is going to get denied now with this one here I'm going to add parentheses because usually with these logic operators and an or you want to use parentheses because sometimes they can get hard to read so if we put parentheses around this entire chunk here we can see that the role must be a guest and anything here must be true so here we're using or so only one of these needs to be true so if it's not Monday that'll be false and let's say today is Wednesday true and Friday false since we have one true that means this entire chunk will be true so we'll have a guest this whole chunk would be true and we can get access granted and of course if all of these fail so if we have a if we're contractor and it's not the weekend remember it's not a weekday and if we're a guest and it's not one of these three days then we'll get access denied because there's no other options so we can see with the initial code we have today and roll set to Tuesday and guest so we don't have anything that handles that so we should get access denied if we try that out so I'm going to run the program and we'll see what happens I'll hop into a terminal and to give this one a go to gorun dot slash exercise slash if Dash else and there we can see we have access is denied because it's Tuesday and a guest if we jump back into our code we can try a different combination let's try Sunday at a contractor so we know if we have a contractor we'll go in here because we have contractor and if it's a not the exclamation point if it's not a weekday then we should get access granted so I have contractor Sunday so we should get access granted for this particular scenario back in our terminal we can run it again as we can see we have access granted this concludes the exercise on if else statements I'll see you in the next presentation [Music] in this video I'll be talking about the switch statement we'll cover basic usage case lists and fall through Behavior first a little bit about switch switch is used to easily check multiple conditions and it's an alternative way to do if else blocks switches execute from top to bottom and they optionally have a default action let's look at a basic example on the left we have an X and that's been assigned to the value of three we then use the switch keyword and we switch on x next we have the case keyword in the case that X is equal to 1 we'll print out one in the case that X is equal to 2 we'll print out two and in the case that x equals a 3 will print out three we then have the default case so whenever the case is not covered instead we'll execute the default and the default case for this particular switch is to print out other and the value of x it's always a good practice to have a default case and that's just in the event that you forget to check for a case at least you have something that will it be executed we're not limited just to switching on integers we can also switch on strings so here on the right we have a string example.com and we're switching on this URL variable that we created right here so we can do the case of example.com we'll print out test in the case of google.com we'll print out live and in any other case so the default case is any other case we'll print out Dev we can also have conditional cases so in this particular switch statement we're creating and assigning a variable and then we're going to switch on it so we're creating a variable name result using Create and assign we're assigning the value of calculates and the function argument of five we then use a semicolon our curly braces and then within those curly braces we have our cases so our first case will execute and result is greater than 10. our second case will be when our result is equal to six then this will execute and the last case if the result is less than 10 then this one will execute we can also have case lists so case lists allows us to check for multiple things in the same case so if we switch on X which would be an integer on this first case if it's either one two or three we'll execute some code in a second case if it's 10 20 or 30 we'll execute this code case lists are useful if you want to take the same action for multiple different values the default behavior for switches and go is to automatically stop executing once one of the cases matches what this means is if we have a letter and it's a space then this case does nothing and none of these will be checked however if we use the fall through keyword then automatically the next case will be executed so for example if we have the letter b equal to I this case will be executed because I is present here we'll print out a vowel the follow through keyword is encountered and we're going to automatically execute the next case even though it's not equal to any of these so we'll print out a vowel and vowels are great the fall through Behavior can be useful if you want to always execute some code regardless of which case was matched let's recap switch can be used to easily check a variable for different values you can use commas to check multiple values on a single case expressions are also allowed as a case you can include function calls mathematical operations and logic Within These cases the fall through keyword will automatically execute the next case even if it doesn't match [Music] okay in this demo we'll be creating a program that utilizes the switch statement once you're ready fire up visual studio code and let's go once we're in Visual Studio code click on the demo folder or on the switch demo so scroll down to the switch folder and then double click on switch.go so you'll see we have a little bit of code here already we have a price function which returns one and some constants we have an economy business and first class we haven't covered const very much but it's just like a variable except you can't change it so const is just short for constant in our main function we're going to create a switch statement so we'll switch on P and we'll create that variable and we'll create the value from the price function we'll then create some cases so we'll use case Expressions so when the case is less than two when p is less than two we'll print out a message so we'll have a cheap item for the message if the case is less than 10 we'll say that it's moderately priced and the default case will be expensive item so remember with cases they're checked from top to bottom so if it's less than two and this executes then this one here will not execute so you won't get cheap item followed by moderately priced item that won't happen so if we have the case of p and the price is one for example so if we scroll up we'll see that our price function does return one so this case will be executed first and then nothing else gets checked after that we're going to create another case so we'll create a ticket and this will be an economy seating ticket then switch on the ticket and the case of an economy ticket we'll print out economy seating in the case of a business ticket we'll print out business seating and in the case of first class we'll print out first class seating any other tickets will have a default I'll just print out other we're using the word economy here because that's defined as a constant here so it's like I said it's just like a variable so we have economy business and first class 0 1 and 2. so we're just working with integers so when we switch on the ticket if the ticket is economy we'll get economy seating it's business business heating first class first class seating anything else then we're gonna get other seating if we take a look at our code we'll see that the first thing that prints out should be cheap item because our price is actually equal to one when we call the function and we have an economy ticket and so we should get economy seating printed out so it should be a cheap item followed by economy seating now I'm going to hop into a terminal and we'll give it a go we can run this with gorun DOT slash demo switch and there we go we have a cheap item and economy seating this concludes the demo on the switch statement I'll see you in the next presentation [Music] in this coding exercise you'll be creating a program that utilizes the switch statement once you're ready fire up visual studio code and let's go once Visual Studio code loads click on the exercise directory we're on the switch exercise so scroll down to switch click it once to open then double click on switch.go as always with the coding exercises give it a go on your own first with the video paused then once completed resume the video for my implementation that way you can see an alternative solution to the problem all right let's go so in this exercise we need to use a switch in order to print out information based on somebody's age so I'm going to copy these requirements and stick them in the main function next I'll be creating the switch statement so we'll switch on age and we'll create that variable right now and we'll set it to be equal to zero remember to include a semicolon at the end that way we're able to create a variable right here in the first case we'll check the newborn requirement so the H has to be zero so when age is equal to zero we'll just print out a newborn toddler's up next so when the age is greater than or equal to 1 and the age is less than or equal to three then we'll print out that we have a toddler next we have child so when the age is less than 13 we'll print out child next we have 18.
so this is teenager so as long as they're younger than 18 we got a teenager and finally if they're over 18 we'll print out adults so when we're working with switches the first case to execute will abort the rest of the processing on the switch so if the age is equal to zero and that checks out then none of this gets executed again that's how we're able to have an age of zero and it's okay right here even though zero is still less than 18 we won't get teenager because this will get triggered first up here and nothing else will be executed so the first one will check for zero and we'll get newborn the second is between ages one and three we'll get toddler if they're under 13 will get child they're under 18. we'll get teenager and any age that's 18 or older will be adults let's run this we have age set to zero right now so we should get newborn when it's printed out so let's hop into a terminal we can run this program with gorun DOT slash exercise switch and see we have newborn let's try another one so if we'll change the age we'll try teenager so we'll just say that they're 14.
and if we give this one a go we have teenager as you can see switches are a little bit more concise and sometimes easier to read than having lots of else if blocks so if you have a scenario with lots of things you need to check usually you'd want to use a switch this concludes the exercise on the switch statement I'll see you in the next presentation [Music] in this video I'll be discussing Loops we'll cover basic Loops while loops and infinite loops so when you're writing programs it's often required to repeat actions in code more than once or to iterate over the items in a collection and these tasks are accomplished by using Loops in go there's only one keyword that we use for looping and that is the four keyword let's take a look at the basic C style Loop so we have the four keyword followed by the initialization statement a condition check and the post Loop statement each one of these portions is separated with semicolons so you have three sections initialization condition and post so we create our loop with the four keyword in our initialization statement we would typically create a new variable and it's usually named I for iteration generally you start at zero but you can start at any point you want we're using the create and assign operator to create I and assign it the value of zero our condition portion of the loop will be checked before every iteration so what's going to happen is we'll create this variable I it's then going to be checked to see if it's less than 10 and then if it is we're going to enter into this Loop so then all the code in here will get executed once execution completes we'll go back up to this post statement and I will be incremented by using the plus plus operator plus plus just adds one to I so in the first iteration I will be zero I is less than 10 because it's zero the code will execute then I will be incremented by 1 and then we'll check again so is I less than 10 it'll be 1 at that point yes it is and we'll execute and this will continue until finally I is equal to 10. once it's 10 this check will fail and it'll be false and then we'll exit out of the loop and continue executing code go does support while Loops however we can only use the four keyword in go since there's only one looping keyword so to create a while loop we'll just use the four keyword and a condition note that the condition must have the variable created beforehand so I needs to exist prior to using this Loop if this happens to evaluate to true then the loop will execute one thing to note with this style of looping is you'll always want to adjust the loop counter within this Loop otherwise it'll just go on forever we also have support for infinite Loops so if we want an infinite Loop we can just use four and then nothing else all we need is our curly braces right here and then the co within is just going to execute over and over and over in order to exit an infinite Loop we'll have to use the break keyword usually you would check so in this case we're checking if something happened is true then we'll break and if it's false then we'll just keep continuing on forever since this is an infinite Loop Loops like this will be used for something like web servers or if you're reading data from some kind of data stream and then you would choose the condition on which to break we also have the continue keyword which can be used to skip the current Loop so we have a typical for Loop where we're setting I to zero as long as less than 10. we've got a loop and we're incrementing one time each iteration within our Loop we have an if statement and we're checking the I with remainder division of Two And if that's equal to zero we'll continue so what this will do is this will skip every iteration where I is an even number that means as soon as continue is hit we'll go straight up here and we'll do the condition check again so this code will never get executed down here if the continue is hit first however if we have an odd number then this will be false and continue will not be executed and therefore we will print out the odd numbers let's recap the four keyword creates a loop we can use the break keyword to exit the loop on a specific condition the initialization variable can be used only within the loop block and the post statement executes every iteration we have three styles of Loops we have the typical Loop where you get to set the variable the condition and how much it changes we have the while while loop where we have a variable created previously and as long as that variable is less than the values applied here then we'll execute the loop always remember to increment that within your Loop otherwise it'll go on forever then we have the intentional infinite Loop where there's nothing right here we just have four and our gorilla braces and that will just go on forever [Music] in this demo we'll be creating a program that utilizes looping once you're ready fire up visual studio code and let's go once Visual Studio code loads click on the demo folder we're on the Loops demo so scroll down to Loops click that and then double click on loops.go we'll be creating a basic for Loop and we'll take the iterator value and add it together to create a sum so the first thing we need to do is create a sum variable and we'll set it to be equal to zero we'll then do a print line that way when we run the program we know what the sum is when we start the program we'll then create our for Loop by creating a new I variable and set it to the value of one as long as I is less than or equal to 10 we'll increment it by 1 and run the loop within the loop we'll take sum and we'll add I to it each Loop iteration will print out some is and we'll print the sum so in our code we're creating a new I variable for this for Loop and we're setting it to be equal to one and as long as I is less than or equal to 10 we'll execute the body of this Loop whatever this Loop body executes and gets the end I will be incremented by 1 and it'll be checked again for this condition and once I is greater than 10 this will evaluate two false then we'll exit out and continue running the program within our Loop body we take the sum which is initially zero and we add I to it I starts at one so first will be plus one then plus two then plus three all the way until I is 10.
before we continue let's run this program and we'll see what kind of output that we get I'm going to hop into a terminal we run this program with go run dot slash demo slash loops and we can see the output starts at 0 1 3 and then eventually we end up at 55.
we hop back into the code we're not going to create another loop and as long as the sum is greater than 10 we'll take the sum minus equals five and then we'll print it out and we'll also note that we're having a decrement operation that will be know that which Loop that we're in so with this Loop we don't create a new variable at all all we're doing is checking if the sum is greater than 10.
we know from the last run that the sum was 55 so it's definitely greater than 10 and this will check out as true we'll then enter into this Loop we'll take the sum which is 55 well minus 5 from it and then it'll get reassigned back into sum well then print out a message that we're decrementing and then the loop will continue and this condition is going to keep being checked until sum is finally less than 10 or less than or equal to 10.
so let's save and run this program and we'll see what we get so here we have at the top it went off the screen but we start at one and then we end up at 55 and now we decrement five at a time so 50 45 40 all the way down until the sum is 10.
one particular thing to remember about this Loop down here on the bottom is we aren't changing the sum within the loop statement itself so here in this for Loop this first one we have the I plus plus at the end which modifies this I which eventually affects this condition none of that is present here on this bottom Loop so if we forget to subtract or add to the sum then this will just go on forever because 55 is greater than 10 and so this is always going to be true and this will just be an infinite Loop so always remember to have something that modifies this expression that way the loop eventually terminates this concludes the demo on Loops I'll see you in the next presentation [Music] in this coding exercise you'll be creating a program that utilizes Loops once you're ready fire up visual studio code and let's go once the visual studio code loads navigate to your exercise directory or on the loops exercise so click on the loops folder and then finally double click on loops.go as always with the coding exercises give it a go on your own first with the video paused then once completed resume the video from my implementation that way you can see an alternative solution to the problem alright let's go so for this exercise we need to implement the classic Fizz Buzz interview problem using a for Loop so I'm going to paste these requirements into the main function so we'll need to make a for Loop and we'll start at one because we need to print out one and as long as it's less than or equal to 50 we'll increment it by one so the first thing that I'm going to do in my version is I'll see if the number is divisible by three so if it's divisible by 3 and to do so we use the remainder Division and we could do by three so this is also called a modulo operation and if that's equal to zero that means it's divisible by three and if we can do divisible by five as well just by changing this to five and now all we need is an if else block so if it's divisible by three and divisible by five then we'll print out fizzbuzz next if it's divisible by three then we'll print out fizz and finally if it's divisible by five we'll print out Buzz lastly if none of these check out then we'll just print out the number so we're creating a for Loop and we're starting at one and as long as it's less than or equal to 50 we're going to keep looping each iteration we're going to increment by one we use the modulo operation to determine if the value of I is divisible by 3. and if it's equal to zero that means it is divisible by three and the same thing goes for five so if it's equal to zero here then is divisible by 5.
if it's both divisible by 3 and 5 we'll print out fizzbuzz if it's just divisible by three we do Fizz and just divisible by five we'll print Buzz otherwise we print the number out we have to make sure that this one comes first because numbers can be divisible by both three and five and if for example we did divisive Y3 and if that was first the number 15 would trigger this one and then this would get ignored and this will get ignored so we may have to make sure that we have it in the correct order I'm going to save this and run it and we'll make sure that it runs properly I'll run this exercise by doing go run dot slash exercise slash oops and so if we start at the top we see we have one two and then Fizz so this would be three which is divisible by three four five Buzz divisible by 5 and here we have nine Etc and here here's 15. this is our first number divisible by both three and five so our program is working properly and we go all the way up to 50 down here which is divisible by five so we print Buzz this concludes the exercise on Loops I'll see you in the next presentation [Music] Google [Music] in this coding exercise we'll be creating a program that reviews some of the topics that we've covered so far in this section that includes control flow and looping and creating variables we'll also be using some new standard Library packages to retrieve the system time and Generate random numbers to access the go package registry you can navigate to this URL right here pkg.go.dev STD open up your browser and navigate there now because we'll be using that shortly once you're ready open up visual studio code and let's go once Visual Studio code loads navigate to your exercise directory we are doing the SR dice project so click on that and then double click on dice.go before I hand off this exercise to you to do on your own let's take a quick look at the Go package library on the internet here I've navigated to pkg.go.dev STD and STD is just short for a standard this page is a listing of all the standard Library functionality that's provided with the go programming language the standard library is just a set of tools you can use to make it more easy to create programs for this particular exercise we're going to be needing random numbers for the dice rolling so you can go down to the math module right here and then click on Rand and Rand just helps Generate random numbers if we scroll down in our rant package you'll see that there is an overview section and a few examples that you can click on we also have the package Index right here which lists out all the functionality available within the back within the package so let's click on the example code it also has some code comments and so it tells us that we can seed our random number generator and seating just sets the initial value and then once our random number generator is seated we can use the Rand dot intend function to select a number within a range so if we scroll down to the intend function right here and click it here we have int n this is the function that you'll need to use within your code in order to complete the exercise all it does is pick a number between 0 and n B parentheses means it does not include n so if you want if you have the n as equal to 5 for example and you want to include it you'll need to have n be 6 that we can get your 5 out we also have example code and it shows you how to use this function now that you have that information let's hop back into Visual Studio code even though we are covering a few new topics in this exercise I would still give it a go on your own first with a video paused then once completed resume the video from my implementation that way you can see an alternative solution to the problem all right let's go so in this exercise we're going to be creating a dice rolling program and we're going to print out information based on what the role is one thing to note about this program is we have to be able to handle any number of dice rolls and sides so we're not going to just be able to pick a number between 0 through 6 or 1 through 6 and then just print out the answers so we have to build a handle multiple dice multiple roles and any number of sides so the first thing I'm going to be doing is importing the packages that we need so we also need the Math slash rant package and the time package from the standard Library once those are imported we can go down into our main function and start working on the program the first thing we should do is seed the random number generator what seeding does is it sets the initial value for the random numbers so if you use the same seed value whenever you run the program you would get the same random numbers back we want to have different random numbers so to do so I'm going to do rand.seed and the seed value is going to be the current time so we can use the time package the Now function and then get the Unix Nano function the Unix Nano function will get the number of nanoseconds since the start of the Unix Epoch which is in the 1970s so since every time I run the program it'll be a different nanosecond hopefully unless you can run it really really fast then the seed will be different and every time we run the program the random dice rolls will be different next I'll set the number of dice that we have and the number of sides on each dice so I'm going to go with two dice and each one has 12 sides I'm also going to set the number of rolls that we'll be doing so we'll set it just one roll for now next we need to create a loop and so since we have multiple dies and multiple roles we should have the rolls be the outer loop so I'll use the variable R to be the outer loop for the number of rolls as long as that's less than or equal to the number of rolls we're going to keep going so one of the requirements is to print out a message if our role total is equal to a certain number so we'll need to keep track of our roll total so I'll just make a variable named sum and we'll set that to zero we're now going to need an inner loop and the inner loop will take care of each dice that's in this particular roll so I'm going to use D for the dice counter I'll set it to one and as long as D is less than or equal to the number of dice that we have we'll increment it since this will be our dice rolling Loop we need to make a function that actually rolls the dice so we're going to create that now I'll name the function roll and we'll just specify the number of sides that we want it's going to return the role that we got back we'll then return Rand and we'll use the intend function that was mentioned at the beginning of the video we'll take the number of sides and we'll add one to it the reason we need to add one to the number of sides is because the int n function starts at zero but dice don't have a zero number they always start at one so we just add one to whatever the result is go back down to our dice rolling Loop we'll create a variable and that will be whatever the role happens to be so we'll roll and we'll roll the U number of sides we'll then add to our sum whatever we happen to roll we want to print out a message so this will be the terminal message that displays what role number we're on uh what dice number we're on and what the role actually was so here we have R which is our current roll number right here we have die number D which is right here and then we have the value that was rolled for that particular die which is calculated right here when we call the roll function the next thing we'll do is print out the total sum for this particular dice roll we're now going to switch on this sum and we're going to print out different messages based on what the total is I'm going to pull in the program requirements so we know exactly what totals we're working with this first one will be snake eyes next we'll do Lucky Seven after that we'll do even and finally we'll do odd we're not going to have a default case because if there's a default case we don't want to print any additional information since that's not part of the requirements so this should be our program completed now we've hit all the requirements we print out all the necessary information we add up the sum and we print out messages based on what that sum is so let's run it remember we have two dice and we have a both of them are 12-sided Dice and we're gonna do one roll so what we should be getting is we should get a roll number printed out along with two dice rolls which side was rolled and the total I'm going to go ahead and save the file and now hop over into a terminal we can run this project with gorun DOT slash exercise slash Sr dice make sure you're in the correct folder gotta be in the in the lectures folder and we'll try that again so here we have our roll number so both of these dice are for roll number one and we have the first one and the second one the first one rolled a three the second rolled a five and the total is eight and that is an even roll I'm going to change the number of roles to make sure that we do handle multiple roles I'm going to change the number of sides to just a typical six sided die so maybe we'll be able to hit some of these cases easier back in our terminal and here we have our second role down here we did roll a seven and so we got the Lucky Seven printed out this concludes the section review exercise on the fundamentals portion of the course I'll see you in the next presentation [Music] before anything else let me congratulate you go is by no means easy to learn and you've already made it a significant way through Jason's full course so for that make sure to Pat yourselves on the back but don't put your feet up to just yet because if you're serious about mastering go your learning can't stop here in fact now is the time to turn it up and take the rest of Jason's complete go boot camp course where there's plenty of more exercises waiting for you plus a very cool pixel project if I do say so myself you can check it out in the description below or just watch the video right there on your screen to see everything you'll learn in the rest of the course one last thing if you enjoyed this crash course the least you could do is show Jason some love by dropping this video a like and letting him know your thoughts in the comments below alright that's it for today and I look forward to seeing you inside the zero to Mastery Academy foreign
Up Next

What Is a Container? Container Technology and Image Layers Explained
@vmwarecloudnativeapps816
679.2K views•2017-05-16

Introduction to Secure Multiparty Computation with Yehuda Lindell
@fhe_org
7.7K views•2021-02-04

HTTP Requests Explained: GET, POST, PUT, DELETE
@codecademy
103.1K views•2021-10-07

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science






![Fundamentos de Programación - CONDICIONALES [ IF - ELSE ], (video 33)](https://i.ytimg.com/vi/ATxSyRAI7bY/maxresdefault.jpg)





























