Golang Tutorial #22 - Interfaces

Tech With Tim · Beginner ·🧠 Large Language Models ·6y ago

Key Takeaways

This video tutorial covers the basics of interfaces in Go, including defining and implementing interfaces, using interfaces as types, and accessing methods through interfaces. The tutorial provides a comprehensive overview of interfaces in Go, including their definition, implementation, and usage.

Full Transcript

[Music] hello everyone and welcome back to the golang tutorial so in this video we're going to be talking about interfaces now interfaces are very important and very powerful inside of golang and in fact inside of any real typed language if you're coming from a more dynamic language like javascript or python you've probably never heard of an interface and in fact you don't really need to use one in those languages i mean i suppose you could but there's not really a real good purpose for it whereas in a language like golang it makes a lot of sense now what is an interface one interface is really a way of looking at a set of related objects or types so let's have a look at this example here to really explain this we have a circle and we have a rectangle and they both have this similar behavior in that we can call area on them i can call a rect area i can call a circle area and they both have a different implementation but they both have an area so in theory you know the rectangle in the circle could be looked at in the lens of they both have an area they're both of shape they both have some kind of area i don't need to know anything more about them other than that they have this area and while i should be able to use that area on them that's kind of what i'm getting at with the interface the interface lets you look at these types as if they're the same it kind of hides the details underneath and says we just care about the fact that these both have area or they both have a perimeter or they both have something right that's when interface lets us do it lets us define some kind of behavior that is similar between objects or similar between types so that we can use these types kind of one in the same with their related behavior now a good example of this is if we wanted to make a slice for example of c1 and r1 so maybe i want to do this i want to say shapes colon equals and i want to make a slice we want it to be some type i don't know what the type is so i'm just going to write type for now and then we want c1 r1 now of course we don't know what to put here and this is going to be an error right we need to put some kind of type when we define this slice but what type do we put here we have no idea right now what i want to do though is i want to look through shapes and i want to call area on both of the shapes i want to be able to do something like shape 0 dot area and shapes 1 dot area and in fact if we look we assume that this is valid it's not but assume it's valid then really this should work right because both the circle and the rectangle have this area method so i should be able to do shape0.area and shapes1.area and that means that maybe if i had a huge slice of shapes i could do a for loop and loop through them and call dot area on all of the shapes and sum up the area right or something like that but right now we can't do that and this is where an interface comes in it lets us do exactly the behavior i'm trying to illustrate to you so i'm just going to define an interface and then we'll talk about it more in depth so i'm going to define type shape interface like that and inside of here i'm going to say area float 64. oh not inside the bracket put it there all right so what i've done now is i've defined a shape interface and all this says all the whole point of this interface is really just to say that anything any type any struct that has this area method that returns float 64 is of type shape it is it implements the interface shape so we say that when some kind of struct so one of these types that we've defined has the behavior defined or has the fields defined inside of this interface that it implements the interface and when it implements the interface we can use the interface as kind of like an upper level type of this struct now i know this is a lot of big words it's confusing we'll see how this makes sense in a second but really just think of the fact that since both circle and rectangle have an area method here they implement this this interface right because all that's said here is if it has area that returns float64 it is a type shape that's what this interface says now if i go ahead in here and i add um i don't know let's just call pow i'm just making up a random one here and we say pow float64 well now both circle and rectangle do not implement the shape interface because they don't have a method called pow that returns float64 that's the basics that's all you really need to know of course if we had a method that took some parameters then i would have to define them in here i would have to say something like x int and now we would need to have not only a method called pow that returned float64 but a method called pow that took a value x that was an integer and returned float64 so that is kind of how the interface works now once we've kind of understand how you implement an interface and really how you define it which i think i've just explained pretty much how do we use it well we use it just like any other type in fact i can actually just plug it right in here and save and this is totally fine what does it say your shapes declared and not used yeah so that's a common error that's not to do with what i've done but see this is how this works since the circle and the rectangle both implement the shape interface i can use the type shape and plug them both inside of this slice now the important thing to understand though is that as soon as i do this as soon as i use an interface as a type all of the other behavior that i know is true about circle and rectangle i cannot access through this interface so i can only use the dot area method on anything inside of shapes because that's all that this knows that i know right if you think about it the only thing similar between the rectangle and the circle is the fact that they have area so since that's defined inside of the shape i can only use dot area when i'm looking at shapes on c1 i can use anything i can call the radius on r1 i can look at the width and the height but on this shapes list right here this shape's um slice i can only use dot area so let me show you what i mean if i do for underscore shape colon equals range shapes oops like that let's go shapes then what i can do is go something like fmt.print not printf i want it to print a line these autocompletions always mess me up all right line and then let's go shape dot area this is valid and i can do this but i could not for example call shape dot radius right and the reason i can't do that is because of course radius is not defined in the type shape so i can only use things that are defined in the interface when i'm accessing the interface which of course makes sense so let's have a look at this now i'm just going to run this down here so go run tutorial.go and we get the area printing out so we have 63 point whatever and 35 and that is the basics of the interface if you implement the interface then you can use the objects inside of here inside of the type interface and use all of the behavior that's defined in the interface it's just a way of looking at objects that implement this type of behavior you look at them in this lens not in the circle lens which would give us access to the radius as well right and that is the basics behind this i don't know what else can we show you let's look at a function so another great thing with interfaces is that you can use them as any kind of type it doesn't just have to be a slice you can use them now as parameter types right as return types you can use them as a variable type whatever you want you can use them in a map right that's why they become so flexible because now you can use all these different types under this interface right so now let's do func get area and let's inside of here actually say we're going to take s which is a shape and then we're going to return a float 64 and all we'll do is return the s dot area so this is very similar to what we've done down here all we're saying is that now we're going to have this function called get area instead of printing shape dot get area let's just print the get area of shape so now i just pass that shape here which could be a circle it could be a rectangle in fact it could be anything that just has an area method on it and then i return s dot area boom we can print that out and this works totally fine again one of the great things with an interface is that we can do that now i just want to show you what happens if i make these methods actually accept the pointer so of course i showed you in the previous videos that pointers and what is it pointers and values are different and we need to understand the difference between them so i need to kind of go over that here if we add this method so it accepts a pointer not just the actual instance or not just the kind of like a copy like we've said before then if i save this we're going to have to change some things so here look what we're getting cannot use c1 type circle as type shape in array or slice literal circle does not implement shape area method has pointer receiver so what this is saying is i cannot use these so c1 and r1 which again is just the it's not the pointer it's kind of like the value right i cannot use that inside of here because how am i going to call area on not a pointer of circle right how am i going to do that well i can't so what i need to do when that's the case is i need to make sure that when i create a slice or i use these as a shape i'm actually passing the pointer so now we're totally fine this works we can do that but that's because again we had the asterisks here so if we remove the asterisks and in fact i can do this now if i just remove it from circle and we save here let's see what we're getting save is it not giving me any error oh yeah i guess i can pass the pointer well now i can not pass the pointer for c1 and this still works but if i try to not pass the pointer for r1 and we save we should get the red squiggly yeah we get the red squiggly popping up so it's good practice to always pass the pointer when you're making kind of slices and stuff like this just so that if you need access to the pointer you have it and it doesn't hurt to pass the pointer because you can still access the methods even if the pointer is there but if you have a method that has the pointer on it then you need to make sure you pass the pointer otherwise it won't implement the interface correctly so i hope that kind of makes sense i understand that's probably a little bit confusing and you need to do some more practice to really understand that but just when you see examples or you see error messages that are telling you like oh it has reference it doesn't have pointers stuff like that mess around with the ampersand and the asterisks because that's probably your error and one of the most common errors i run into all the time writing go code is the fact that i'm mismatching pointers and types or pointers and references and values and all that stuff so that is kind of it for interfaces the last thing i will say is that objects can implement different interfaces so you don't only have to have one interface they can actually implement three four five as many interfaces as you want and in fact i can actually go type shape two interface and then here go area float 64. and now technically both my circle and my rectangle implement the shape interface and the shape 2 interface right and now shape 2 is just a different name to look at my objects and in fact it's going to be the same view but i could have made this a different method right so if i made this now perim so maybe that's perimeter then if i wanted these two objects to implement this interface and this interface i would need to make sure that i add perimeter to a circle and two rect so add methods for a perimeter and then they would implement both of those so i hope that makes sense again that has been interfaces that's really all i can show you there's not too much more to go through but i would encourage you guys to kind of look them up practice with them a little bit because they are very important and they're really useful to understand that this is kind of the way we view these structs and that when we're viewing them in this way we can only access or perform any of the behavior that's defined in this kind of view that's the way i like to think about it again hopefully that makes sense let me know in the comments down below with that being said i hope you guys enjoyed if you did make sure to leave a like subscribe and i will see you in another youtube video

Original Description

In this golang programming tutorial I will be convering go interfaces. Interfaces in golang are a way to group structs that have related behaviour. Structs can implement an interface and you can use the interface name to access related methods or behaviour of all structs that implement that interface. 🎙 Subscribe to my second channel for weekly podcasts! https://www.youtube.com/channel/UCSATlCAUi7R0Ik-wsZb2gOA ◾◾◾◾◾ 💻 Enroll in The Fundamentals of Programming w/ Python https://tech-with-tim.teachable.com/p/the-fundamentals-of-programming-with-python 👕 Merchandise: https://teespring.com/stores/tech-with-tim-merch-shop 📸 Instagram: https://www.instagram.com/tech_with_tim 🌎 Website https://techwithtim.net 📱 Twitter: https://twitter.com/TechWithTimm ⭐ Discord: https://discord.gg/pr2k55t 📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/ 📂 GitHub: https://github.com/techwithtim 🔊 Podcast: https://anchor.fm/tech-with-tim 💵 One-Time Donations: https://www.paypal.com/donate/?token=m_JfrPK7DsK4PLk0CxNnv4VPutjqSldorAmgQIQnMozUwwQw93vdul-yhU06IwAuig15uG&country.x=CA&locale.x= 💰 Patreon: https://www.patreon.com/techwithtim ◾◾◾◾◾◾ ⚡ Please leave a LIKE and SUBSCRIBE for more content! ⚡ ⭐ Tags ⭐ - Tech With Tim - Golang Tutorial - Go Programming Tutorial - Golang Interfaces - Interfaces Golang - Go Interfaces ⭐ Hashtags ⭐ #GO #Golang
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video tutorial teaches the basics of interfaces in Go, including their definition, implementation, and usage. It covers how to define and implement interfaces, use interfaces as types, and access methods through interfaces. The tutorial provides a comprehensive overview of interfaces in Go, including their benefits and common use cases.

Key Takeaways
  1. Define an interface with the `type` keyword followed by the interface name and then the methods that the interface will implement.
  2. Implement an interface with methods that are implemented by other types.
  3. Use a type that implements an interface as if it were of the interface type.
  4. Access methods of the interface type, not methods of the underlying type.
  5. Use an interface as a parameter type, return type, or variable type.
  6. Pass pointers when making slices or arrays.
  7. Implement multiple interfaces on objects.
💡 Interfaces in Go provide a way to define a common behavior that can be used with different types, allowing for more flexibility and generic code.

Related Reads

📰
Claude Sonnet 5 Just Launched. Is It Actually Better Or Just Newer?
Learn how Claude Sonnet 5 compares to other models like Opus 4.8 and GPT 5.6 in terms of pricing, performance, and benchmarking, and understand what these differences mean for your projects
Medium · AI
📰
Claude Sonnet 5 Just Launched. Is It Actually Better Or Just Newer?
Learn how Claude Sonnet 5 compares to Frontier models in pricing, performance, and benchmarking, and what this means for your ML projects
Medium · Machine Learning
📰
Claude Sonnet 5 Just Launched. Is It Actually Better Or Just Newer?
Learn how Claude Sonnet 5 compares to Frontier models in terms of pricing, performance, and benchmarking, and understand what these differences mean for your projects
Medium · LLM
📰
Claude Sonnet 5 Didn’t Just Get Smarter. It Changed the Economics of AI.
Claude Sonnet 5's advancements have transformed the economics of AI, making it more viable for production
Medium · LLM
Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →