go generics tutorial - golang finally has generics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today i'm going to show you how you can turn this into this [Music] hello and welcome fellow coders my name is thomas and i'm so excited about today's topic soon i'm going to be encoder 7 because goling is finally getting generics let me explain to you why i think this is a huge deal i guess every single developer has written a fair share of some functions over the course of their lives many even in different languages this is because the sum function is one of these functions you see in basically every single beginner's tutorial here we have python and javascript and here we have golang golang what the actual but thanks to go 118 we are finally getting the solution to this particular problem and it is called generics according to a go developer survey that was conducted 2020 generics are one of the top three problems to fix in the language so they must be important right yeah kinda but what exactly are generics and how do they help us clean up this mess generics help you write functions using types that can be specified later so basically they help us write functionality in a more abstract way let's again have a look at the sum examples and see how generics would affect them all function bodies look completely identical the only thing that is different is the function signature or in more detail the function argument as well as the return type and since method overwriting is not allowed in go you are forced to name all functions differently as well but they all do the exact same thing they take two arguments and return their sum the sum strings function might not be the best example but for educational purposes let's just go with it so in order to accomplish the exact same thing for different types golang forces you to duplicate code thanks go now let's see where exactly generics come into play as i said earlier generics let you write functions using types that can be specified later so basically we take all different types and merge them together into one type a generic type you would take the variable of whatever type and replace it with a generic type all of a sudden all functions are completely identical even though the syntax is incorrect which is why my ide is underlining it red the basic principle should be clear you define a universally valid function by using generic types and since all these functions are now the same we can get rid of the duplicates amazing stuff am i right but unfortunately you cannot use generics yet as of now go 118 is expected to be released early this year so there might be some slight changes to come but i was too excited about golling finally getting generics then i couldn't wait to do a video about them okay calm down but before we jump into the coding part let's first have a look at the proposal of generics here it states that the developers suggest extending the go language to add additional type parameters to type functions and declarations type parameters are constrained by interface types interface types when used as time constraints support embedding additional elements that may be used to limit the set of types that satisfy the constraint well this couldn't be much clearer right let me try to translate it into human language they suggest adding type parameters to types and functions these type parameters are defined using constraints they in turn define allow types methods and operations available for the specified generic type so they constrain what you can do with the variables of that type hence the name and golling internally uses interfaces to accomplish these constraints ok if this still sounds like sciencey gibberish to you just remember these two key points generics are additional type parameters which are constrained now let us hop over to the playground and finally see generics in action let's go the code you see right here is the same as in the earlier example three different sum functions for three different argument types the first thing we need to do is to switch to the death branch this way we can get access to generics and play around with them let's take the very first sum function and rewrite it using generics as i said earlier in order to use generics you need to consider two things the type parameter and its constraint the first thing we need to do is to define a generic type parameter within square brackets in front of the argument list let's call it capital t for type as for the constraint bowling already provides us with a set of predefined constraints we will first use the anyconstraint which is basically the interface of type parameters we also need to change the type of the function arguments to t as well as the return type and that's basically it for our first generic function let's also rename it to sum within the main we can now change every function call to sum and run our code wait this doesn't seem to work it says that the plus operator is not defined for the constraint any well that is unfortunate but it also makes total sense since we are trying to operate on our variable of type t we have to make sure that the constraint we are choosing actually allows us to use the operator in our case it's the plus operator and apparently the any constraint does not allow the plus operator so what now the good thing is that go 118 comes with a whole bunch of predefined constraints so in order to fix our compilation problem let's try the integer constraint first we need to import the constraints package and then we can use the integer constraint right here the code now compiles but running it now gives us another error it says that string and flow do not implement the constrained integer i would like to draw your attention to the exact wording here it says that string does not implement constrain point integer this is because constraints are actually interfaces in goaling keep that in mind i will come back to this point later on but first let's fix the sum function heading back to the list of predefined constraints we can see that order implements in float and string this is exactly what we are looking for so let's use that instead of integer and the code seems to work congratulations we have written our very first fully functional generic functioning goal and we also have replaced three basically identical functions by one generic function and boy oh boy does this have applications finally no more code redundancy for simple functions no more passing in interface and type checking afterwards all in all we get the ability to write our functions in a more abstract and generic way there is one final thing i would like to show you remember when i told you that constraints are actually interfaces we will make use of that and write our own custom constraint let's go if you take a look at this generic max function you will probably see why this is not going to work pause the video and give yourself some time to think about it it will test if you fully understood generics you probably already spotted it we are using the greater than operator on a type parameter t which is again constrained by any and the operator is not defined for any so to fix this i'm going to define an ordered interface and pass in types just like in the constraints package but way less types though let us just go with int and float64 if we run the example we can see that the max function now works just fine for ins and floats but this is not where the magic ends just for the giggles let's define our own type called weekday of underlying typeint and then create our constant weekdays in order to find out the latest weekday we would pass in a slice of weekdays to our max function executing the main function obviously does not work since max is only able to apply the greater than operator on ins and floats the error message is also pretty clear it says that weekday does not implement ordered so let's simply do that and add weekday to our ordered constraint running the code will now pick out the maximum value which in our case is the integer value for sunday pretty awesome right so how do you feel about generics are you as excited as i am do you think it is something that golem needs to become the number one language of the world or is it just syntactic sugar let me know in the comments down below thank you so much for watching my take on going generics [Music] no the other way around generics and go i hope you enjoyed watching this video and maybe learned something along the way if you did give this video a thumbs up it will help the almighty algorithm to bring my content to more people around the world if you are new to this channel and want to see more tutorials like this please subscribe and leave a comment with one more tutorial so i know you guys want to see more of me i mean my content and until next time keep on coding [Music]
Info
Channel: Thomas Langhorst
Views: 5,344
Rating: undefined out of 5
Keywords: golang tutorial, tutorial, how to, how-to, generics, golang generics, generics in go
Id: A8_sZ3mC7Rw
Channel Id: undefined
Length: 8min 32sec (512 seconds)
Published: Sun Jan 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.