Go Tutorial - INTERFACES Part 2 (Empty Interfaces, Type Assertions, Type Switch)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to this tutorial on go interfaces thank you for tuning in this is the second part of what is going to end up being a four-part series covering golang interfaces if you're completely new to the concept of interfaces in go i strongly recommend that you watch the first video part one of this series golang interfaces operate slightly different than the interfaces in some other programming languages and that first tutorial will provide you with a foundational understanding as well as some key concepts like abstract and concrete types this video will cover slightly more advanced topics and assumes that you already know the basics as the agenda states here in this tutorial i'll discuss type assertions empty interfaces and the type switch statement and then i'll finish up discussing what you can expect in the next video of this series so let's get started in the last video i provided an example of a golan interface by declaring this shape interface i then show that you could create a struct like this one of type rectangle with various properties and methods two of which are defined in the shape interface meaning that it satisfies that interface you can then create a function that accepts a shape interface like this calculate function then within our main method we created an instance of the rectangle and so that you can pass that rectangle instance into the calculate function as a parameter of type shape and call the interface methods at the end i pose the question if we wanted to call the rectangle method get sides from within the calculate function how would we do that and just to make sure you guys are following me this is what i'm saying if we change the calculate function to accept a rectangle type instead there's no question that go would allow us to call all three of these methods from within the calculate function right at that point it's just the standard parameter but our function accepts a shape interface which doesn't define a git size function so calling something like s dot get sides is not allowed that's where type assertion comes in type assertion lets us extract the value of the underlying type that gets passed in which is a rectangle then call the methods on that return value the reason we're able to do this is because when we pass in an instance as a interface parameter that instance still has an underlying type in value in our case the type is rectangle and the value is the value or values associated with the instance of that struct that was passed in we can then call the methods on that instance value that gets returned but in order to do this we have to tell the program or make a type assertion about the underlying type of that interface and like i said once we do that we're able to extract that value stored in a variable and then we can call the methods on that variable variable because now that variable has a type and value equal to the underlying type and value of that interface if that sounds confusing don't worry about it i'm going to hop over to the code and i'll illustrate this further all right so again this is the code that we put together in the previous video part one of this series covering interfaces if this code looks confusing or foreign to you please do go check out that video up top here we have define our interfaces we have our functions here and then in the main method we create an instance of the rectangle and make a call to that calculate function where we pass in that instance before i show you how to do a type assertion i just kind of want to illustrate what i mean when i say these interfaces have an underlying type and value so for this parameter that gets passed then i can use interpolation along with these template strings percent t and percent v to print out the type and value of the underlying struct within this interface and when i print that out you can see here at the right that it says my type is main.rectangle because it's from the main package and then it's got my type and then the values of each one of those fields within that struct so we can see that that pass then parameter has an underlying type and value it's in there somewhere we just need to use type assertion to extract it out and when you do that you're extracting it out into a new variable this is what it would look like line 43 is where i've performed the type assertion in the syntax for this is to use the variable that you are making an assertion about followed by a period and then in parentheses you place the type that you are saying is the underlying value of this interface and we do that because at this point the go program doesn't see this parameter as a rectangle it sees it as a shape interface now that the underlying value has been extracted into this new variable called rect we can call all of the methods of a rectangle just by you know simply putting them in this print line function and having them printed to the console so that's the first way you can use type assertion which is to make an assertion about the underlying type of the passed in interface the other way you can use type assertion is to assert about an interface you can assert that the variable implements another type of interface it's possible for a variable or a type to implement two different interfaces and in that case what gets returned is a variable still having the underlying type and value but the program now recognizes it as an interface the same interface that you asserted was in that original variable for example let's say that the rectangle struct also implemented a second interface called polygon which declares the getside's function now within this calculate function we can assert that the passed in parameter implements the polygon interface as well aside from that we don't need to change anything else in our code so you can kind of see this as saying you know we're making the claim that this parameter implements this interface or in the case of a you know actual type or struct that we're making an assertion on we're making the claim that this is the underlying type and when we run the program and print out the results we see that the results are the exact same as the previous type assertion now one thing to be aware of with type assertions is that it is completely possible to make the wrong type of assertion we know that we're passing in a rectangle into this calculate function but if i was to say well i want to make the claim that this passed in parameter is of type circle what happens is that your go program will panic and if you're not familiar with what a panic is a panic is just a runtime error and go it's something you always want to avoid it basically means your program is hidden error and it's shutting down it's no longer going to execute anything so while we can certainly make type assertions in the way that i've done it so far best practice is to do it slightly different because we don't want to put our program in a state that it can't recover from the way that we do this is really simple instead of returning one variable that would hold our value we're going to return two variables so we just add a second one here the variable's called okay and we're going to include this type assertion we're going to stick all of this into an if statement and if you haven't seen this type of syntax around an if statement it's just a way for us to declare a variable and check the value of a variable all in one statement so we're declaring a variable rect which of course is going to hold the value and we're declaring a variable okay which is of type boolean and the value of okay is going to be true or false depending on whether or not we have made an assertion about the correct type contained within that value and the value of okay is going to be true or false depending on whether or not we have made a correct assertion about the underlying type of that variable so we're correct obviously it's going to be true if we're wrong then it's going to be set to false and so this statement then checks the value of okay so we're saying you know we're going to declare these variables and if okay is true then go ahead and execute the following code and what we've done now is kind of implemented this safeguard and protected ourselves against a panic in a circumstance you know where we're asserting the wrong type because we're saying let's check and verify that we've asserted the correct thing before we try to execute any other code now let's move on to discussing the empty interface when i first started learning golang there was a point at which i understood interfaces i knew how to use them i knew how to implement them and then i came across this thing here empty interface and was just very confused but i want to let you guys know that the empty interface is a very simple concept and it's really nothing special about it i really think that it's just the syntax in the way that it looks that causes some confusion among new go developers but i promise if you understand everything i've explained so far you're going to understand this very quickly and just to kind of explain this let's look at the interface that we've already covered the shape interface we discussed the syntax for declaring this interface and what it means to actually satisfy the interface for a type to satisfy it it needs to implement both of these methods and it's okay if the type has more than just these two methods but at the very least it must have an area and perimeter method that returns a float64 what if we define the interface like this instead well now of course the type only needs to implement the area method to satisfy that requirement what about now well now the type can have zero or more methods because there are no methods defined in this interface and every type and go has zero or more methods and that's all an empty interface is it's just a placeholder it's a placeholder that can stand in for any and every type in go because all types implement zero or more methods i can illustrate this further in our code if we go back to the code here what we see is that we can actually change the parameter type of this calculate function to an empty interface and everything still works fine still has an underlying type and an underlying value and we can even declare a variable of type empty interface at the top here and what that means is that any value can be stored within that variable i'll illustrate that down here i can store a string an integer a boolean into this variable i it doesn't matter because they all satisfy that empty interface one of the places you'll sometimes see that empty interface syntax is when you see a map of type string to empty interface and what that means is that the individual values of the map can be any value if you've worked with the json marshalling and unmarshaling functions sometimes you'll see that we unmarcel json objects into a map of string interface and that's because json objects can contain various types so a map of string interface will hold whatever value and type that json object has in it the last thing i'll discuss in this video is types with statements type switch statements are similar to switz case statements in the sense that they are an alternative to creating or writing multiple else if statements within your code in the examples that i've covered today we already know the underlying type and value of the interface being passed in but in real world examples you often don't know what the underlying type and value is often you're working with someone else's code or you don't know what the parameter is that's going to be passed into your function in this situation there may be specific lines of code that you only want to be executed depending on the underlying type of that variable which as i said you may not know so if we didn't know the underlying type of this parameter s we could write a collection of if and else if statements to check that underlying type and then execute code accordingly and we can add an else statement at the end here as kind of a default case to execute this line of code if none of the other statements are run so all of this would be pretty easy to follow and understand and the type switch statement is just an alternative to that in order to write a type switch statement you just use the keyword switch followed by the variable that we want the return value to be stored in and then we can create cases that will run code depending on whether or not the type defined in the case matches the underlying type of the variable stored in x and the default case at the end is kind of like that last else statement if all else fails then we're going to run this default case that does it for this second video covering golang interfaces in this tutorial we've discussed type assertions empty interfaces and types with statements if you guys have any questions or feedback please let me know in the comments in the next video we'll be taking it a step further and discussing go lane reflection please subscribe if you guys would like to see more videos like this subscribing really does help it truly truly is appreciated otherwise i'll see you guys in the next video on esoteric tech thanks for watching
Info
Channel: Esoteric Tech
Views: 1,508
Rating: undefined out of 5
Keywords: go, go interface tutorial, go programming language, go programming tutorial, go type assertion, golang, golang interface, golang interface tutorial, golang tutorial, interface, interface golang, interface programming, interfaces, programming, tutorial, type assertion, empty interface, type assertion in golang, go tutorial for beginners, golang course, golang tutorial for beginners, type switch
Id: YInvSSbGG7k
Channel Id: undefined
Length: 15min 8sec (908 seconds)
Published: Mon Feb 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.