Go Tutorial #7 - Functions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome to this tutorial on esoteric tech the topic of this lesson today will be functions if go was the first programming language that you've ever worked with i can promise that this video is going to be very informative very educational if go is not your first language you'll be happy to know that go is similar to languages like python and javascript in the sense that it handles functions like first class functions but similar to the structs and go go has its own twist on functions some are improvements and some are kind of experiments that should be avoided and we'll discuss both within this lesson so far we've seen functions being used in pretty much every tutorial that i've done the common function has been the format.printline function which prints something out to the console but we've also seen the main function which is the entry point to all programs and it's kind of a special function that automatically gets run whenever you execute a go program so we'll talk about that more but this is kind of the agenda for the day we'll first talk about why we use functions we'll discuss and go through how to define them we'll give an example of how to create custom functions and then i'll discuss what to expect in the next lesson because functions are such a large topic there's no way i can cover all of it in one and as usual if you guys find these tutorials to be helpful please do subscribe and like that feedback is always appreciated so let's get started why use functions well functions give us the ability to reuse codes that we don't have to keep writing the same thing over and over again and i'll give you an example of that in a bit but functions also give us the ability to write clean modular code and i've got an example of that below with this picture of a desktop most people probably haven't ever bothered to assemble their own desktop but if you have you realize that most of the pieces within the desktop are very modular they can be swiped out easily for upgrades so if you wanted to replace the hard drive or the cpu you can go out and buy another component and upgraded component and switch that out as long as it has the same connection so really as long as it receives the same input and gives the same type of output it can be easily replaced and that's what i mean by modular and we'll give an example of that later but as i mentioned it allows you to reuse code so one function that we've seen a lot is this format dot print line function and at the bottom here i've actually got the actual documentation from the golang website of the print line function and we can see here that whenever you call this function it actually returns the output of another function f dot print line and that function is defined right above and so essentially whenever we call this print line function recalling f print line with a few additional parameters and it's executing all of that code within that function so imagine if you had to write that code every single time you wanted to print something out to the console thankfully we don't because functions exist and so functions as you can see save us quite a bit of effort and time in terms of not having to re-type things over and over again and at a high level functions are really about inputs and outputs it's about providing your function with some data some input something to work with it performs some type of calculation or some job and then it creates an output and that output can be in different forms it may be printing to the console with maybe returning an actual value but as i said at a high level is about inputs and outputs so how do we define a function well there are four key parts to defining a function the first one is the keyword func and that's obviously sort for function the second part is to actually use the name of the function that you want to give so if i want to create a function called calculate sum that's exactly what i put in there and then that is followed up by the parameters to that function so in this function that i'm creating i want to pass in two numbers and you always follow up the name of the parameter with the type so this was just taking you know one parameter i just would have said int but because i'm using two i need to separate them with the comma and your parameters are always placed inside of parentheses and then the last part to defining a function is actually to indicate the return type not all functions have a return type it's possible to you know have a function that doesn't return any type of value from it but if it does then you need to indicate that type and it's also worth noting that if your function is returning some value then you have to use the return keyword as indicated here in this function it's also possible to return more than one value from a function and i'll give an example of that as well but i think that's enough theory for now let's go ahead and hop over to the code and i'll show you guys some examples all right so here we are in our main.go file now normally when i switch over to the coding portion of these tutorials the main function has already been typed out but for the sake of this tutorial since we are covering functions i haven't done that yet so as i mentioned you always need the main function to execute a go program the one exception where you do not need a main function is if you are writing a package to be imported as a library for another golang program but in order to execute a program you always need that name function so as i said you always start with the funk keyword followed by the name of the function the main function takes no parameters it has no return types and i'm not sure if i mentioned this but all logic for a function has to be enclosed within curly braces with other programming languages it's okay to have that opening curly brace on its own line but with go that is not allowed you always have to have that opening curly brace on the first line that the function is defined on so we're just going to play around with that calculate function that i just showed you guys in the powerpoint uh so first thing i'm going to do is just going to find define a couple of variables so i'll do first nums equal to 2 and i'll do second num is equal to 4. so those are going to be our inputs our parameters into that calculate function and i believe the name of the function was calculate uh sum and it took in a couple parameters second now okay and so and actually i'm gonna have that return uh of variable so we'll say my sum is equal to calculate sum right and so now it's giving us that error there because we have an actually defined this function so to do that i'll go down a couple lines and got that funk keyword calculate sum and then we said we're gonna put in the parameters you type the name followed by the type and so uh and it's also it's also key to note that the name of the parameters have nothing to do with the actual variable names that are being passed in it can be completely different so i can put num one which is a type int and i can put number two which is also of type it one thing i could also do because both of these are integers is i could actually just have it in there once and separate these with commas and say number two like that so that works and this only works here because both of these parameters are the same type but if they were different then i'd have to follow both of them up with their defined types now as i said the next part is to actually indicate the return type so this function returns an integer and then within curly braces is where i'm actually going to write my logic so i'm going to just type in return number one plus number two right and so one thing i could have done is you know create a variable on this line here and store number one plus number two in that variable then return that variable but that's just more that's more typing that's more code so it's easier just to return the result of number one plus number two and it that returns this integer so that's going to get stored in my sum here and then i can print out that variable here so format.line my sum and then we'll run this and we can see that the result is 6 there also i could have just taken this whole expression here taking this expression here and just put it straight into the format dot print line and there's no need to actually even create another variable i could have done it this way and if i run it you'll see that we get the exact same result i also mentioned that it's possible to return two different values or just multiple values from a function you can return two three or more however in most cases you don't want to return more than two return types but for example here let's say i wanted to return two integers and instead of calculating just the sum i'm going to calculate the sum and difference here right so oops if i can spell right calculate sum and difference and then instead of returning just one value i actually will store these in a variable now so we'll say my sum is equal to num one plus number two and we'll say that the difference is equal to number two minus number one right change this to this and then what we can do here is return both of those values so my sum comma my diff and because we're returning to now you should be able to easily see those get printed out and then also the reason it's giving me an error here is because whenever you're returning more than one value those have to be in parentheses as well so i'll run this code here and we can see that we get two returned values another unique features of functions and go is that you can actually give names to the return type so if i wanted to actually declare these variables here i could do that and then instead of this colon equals operator which is only used when you are initializing a new variable you just use the equal operator because we've already declared it uh now we're just giving it a value and so again i'll run that and we'll see that we get the same result now one thing you may have noticed with the format.printline function is that we can pass in any number of strings and it works just fine but with the functions that we've defined here this calculates sum and difference we've defined it to only take in two parameters so if we tried to pass in the third one we'd get a compile error and the reason that print line is able to do that is because golang supports what's called variatic functions and what that means is that we can define a function that passes in basically an unknown number of values and it will handle that just fine as long as we've declared the parameters to be able to accept that and so let's say i wanted to just go back to a function that calculates the sum here right and instead of returning two values i'm just going to return one in order to notate that i want to pass in a you know unpredictable or undecided number of values what you do is create of course the name of the parameter just like normal but in front of the type you include three periods and that means that this is now a bariatic function and i'm going to get rid of this logic here and so now uh we can pass in any given number of values so let's say that you know we pass in these two well both of these now get stored into this variable valves which is actually a slice now and so let's say i want to store those within this new variable called sum what i can do is actually create a for loop to loop through this slice of values called valves so i'm going to use that syntax that we've discussed in the previous video for index when i'm not going to use that variable so i'm going to leave it as an underline for index comma i'll say v and range vowels and i'm going to add this to the sum oops sum plus equals v right and then we're going to return the sum there so now i can run this and we get six and i can actually put in any number of variables here i can put in eight i can put in nine oops let me get rid of that space there 9. 5. i can run that again and we get those values one thing i could also do is replace all of these input values with a slice actually so i could say i want to pass in a slice of integer of integer and then place values within this slice that i can still use those variables up top second num uh but if i'm going to use in i'm going to pass in a slice as a variatic parameter then i have to use the three dots here as well otherwise it'll give me a compile error so i can run this and we see that we get that result so again if i'm going to use a slice as a variatic parameter i wouldn't have been able to do something like this you know with the comma in between that's not allowed and just to be clear on what's happening here whenever you create this variatic parameter whatever you passed in gets put into a slice in fact if i hover over you can see there that it's saying this is a slice of integer so it doesn't matter whether you actually pass in a slice or you pass in individual parameters they all get put in or copied over into this slice here and that's why most of the time where you see a function that accepts variatic parameters most of the time the function will include some type of looping statement that that it you know goes through and iterates through this actual parameter variable in order to perform some type of manipulation or copy them over or something like that now there are a couple more things i want to show you guys in regards to returning values from a function the first thing is something that you will often see in code and i want to make sure you guys understand it when you see it so i'm going to change this function and by the way if i haven't used this term already when we're talking about uh the parameters and the return type of a function that's often known as the function signature so whenever you hear someone use that term you know what's the function signature that's what they're referring to what's the what's the input parameters and what does it return but i'm going to change this function around here okay so i've now made changes to this code here and the first thing that i want to do is draw your attention to this error package that i have imported now and the reason i'm importing this package is because for this function calculate remainder i'm now returning this error type which is defined within this package and so this calculate remainder function takes in a numerator and denominator it first determines if the denominator is equal to 0 because if that is the case we cannot determine the remainder so what we do is generate an instance of an error type and the syntax for that or the function for that is errors dot new and then you pass in this string value here so if that's the case what we do is actually return 0 for this integer value and then return the instance that we created on this line as the second return type if the denominator is not zero then that means we can determine the remainder uh we calculate that and then we return the remainder and then for the second value we return nil because nil is actually the zero default value of this error type here and that's essentially saying that no error was found and so the reason i'm i'm mentioning this is this because you will often see uh functions in code if you were to go through you know the packages the golang libraries uh you'll often see functions that are returning a second value of type errors and in regards to calling this function what you'll see is that you know you generate or create two different variables so here i'm uh initializing a variable called remainder and another one called error and then what we'll do is actually uh implement some code that performs a check on the value of error so what we'll say is if error is not equal to nil because that's our goal hopefully error is equal to nil which means no error was returned but if an error was returned then we say format dot print line errors that we we know what the error was otherwise we're going to do format dot print line and we're going to print the remainder here right so in this case we shouldn't have any issues there should be no error so we have a remainder of one but if i was to change that denominator which is actually this one here to zero what we'll see is that this line gets run here cannot divide by zero so just again wanted to bring that to your attention uh and then the second thing as i mentioned is that uh just like we can with the you know for loops uh using underscore uh for a variable that we don't want to use we can do the same thing here so if i wanted to say maybe maybe i just want to call a function that checks to see if an error is returned and you know i never intend to do anything with the other return value in that case i can just use an underscore and that's completely fine and it's complaining here because i need to close that off there and so i run that and again that's not a problem that we have this underscore because we're not using that variable so i think what i've talked about so far is enough for this video in the next video what i want to do is elaborate on a term that i use earlier which was first class functions and what that means is that in go you can actually create variables that themselves hold functions in addition you can create functions that accept and return other functions and i think it's appropriate that that information or that content is included in a tutorial all to itself because that can be overwhelming so hopefully this was helpful and make sense for those of you who are completely new to the concept of functions uh if it was not please do ask questions let me know in the comments again please like and subscribe and i hope to see you guys in the next tutorial here on esoteric tech thanks for watching
Info
Channel: Esoteric Tech
Views: 481
Rating: undefined out of 5
Keywords: golang, go functions, go functions syntax, golang introduction, Golang Tutorial, golang functions, Golang For Beginners, Golang Programming, Go Tutorial, golang programming language, golang tutorial for beginners, learn golang, golang beginner tutorial, go language introduction, golang tutorials, Golang SDK, Go Installation, programming tutorial, introduction to go, Learn go, golang installation, go programming tutorial for beginners
Id: FwUbBCWrAnc
Channel Id: undefined
Length: 21min 34sec (1294 seconds)
Published: Mon Mar 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.