Structs - Go Programming Tutorial #7

NeuralNine · Beginner ·🛠️ AI Tools & Apps ·5y ago

Key Takeaways

This video tutorial covers the basics of structs in the Go programming language, including defining and creating structs, adding methods, and implementing interfaces for dynamic behavior. It provides hands-on examples and code snippets to demonstrate key concepts.

Full Transcript

[Music] what is going on guys welcome back to the go programming tutorial series in today's video we're going to talk about structs so let's get right into it all right now one thing that you need to know about the go programming language is that it is not object oriented we don't have classes and we don't have objects what we do have however are structs and structs are basically data structures you can say they can have attributes properties they can have functions and they can even have constructors but they're done in a different way it works in a different way and we don't have any classes and objects in go because go is a very simple language it likes to keep things simple so we don't have object orientation however in order to define a struct let's say we want to have a computer object for example or a computer structure would be the proper term if you want to have a computer structure in go what you do is you say type this is the first keyword then the name of your struct so for example type computer and then the keyword struct in the end so type computer struct and then we open up these curly brackets here and in between those we put some attributes so for example a computer can have a manufacturer manufacturer like that and this is going to be a string manufact and manufacturer command like that um this is going to be a string then we can also have ram for example and ram is going to be an integer in gigabytes uh we're going to have um [Music] for example a cpu brand which is going to be a string and we're going to have a boolean which is going to tell us if this computer is a laptop or not so true or false uh and we don't need the commas here by the way there you go so this is a computer and it has those four fields and now in order to create an instance of that computer object what i have to do and go is i have to say something like comp one is equal to and then i can say computer opening up these curly brackets and then i can say like in a dictionary manufacturer is for example lenovo and then i can say ram is 16 gigs cpu brand is amd and laptop is true there you go so this is now my computer and i can go ahead and say stuff like fmt dot print line and i can print this computer object as a whole and we're going to see that the values are in there as you can see here but i can also go ahead and say for example give me comp 1 dot ram so i'm only interested in the ram and if i want to do that i'm going to just get 16 as a result here so i can access these fields by using the dot operator so this is very simple now what we can do here instead of doing it like that we can also build a constructor now this is not mandatory but we can do it and it is considered i don't want to say best practice maybe it is best practice but it's definitely a good practice to have constructors here and how do you do a constructor how do we create a constructor we create a function which we call for example new computer and this function is going to return a computer pointer we talked about pointers in the last video uh and the parameters here are going to be manufacturer which is going to be a string or let's go ahead and just call them m string r int c string and l just keep things simple here this is not best practice obviously so what we can do here is we can create a new computer we're going to call it or actually c is already used we're going to call it cmp and cmp is going to be a computer with a manufacturer which is going to be m with the ram that is going to be r with the cpu brand that is going to be c and with a laptop boolean which is going to be l and then we're going to just return and cmp so we're going to return the pointer to this computer object so this would be a basic constructor and we can actually create a second computer here which is going to be new computer and here we're going to see dell we're going to have 32 gigs of ram we're going to have intel and this is not going to be a laptop there you go and we're going to print that as a whole object and we're going to see that this also works so this is how you build a constructor now i think we have to de-reference it if we don't want to have the pointer element here there you go um but this is how you build a basic constructor now what you can also do is we can have a default constructor now there's one problem with that however in go and they did this consciously you cannot overload methods so you cannot say okay i have another new computer uh where i say function new computer and it has a different signature and thus it's okay this would be possible in java for example it is also not possible in python but what we can do in python at least is we can say something like okay we have m and m as a string but m is optional by setting it to a default value this is also not possible in go if you want to have a default constructor in addition to that constructor and go you would have to call it something else so you would have to call it for example new computer default if you want to and then you don't pass any parameters and you say okay it also returns a computer pointer and you create a computer object here which has a manufacturer empty string and or you can say default it has a default of 4 gigs of ram and a cpu brand which is also default and it's not a laptop for example this would also be possible so we can go and we need of course to return it turn and cmp and we can go ahead and say com3 is going to be this new computer default uh what do we have here oh default there you go um and then we can go ahead and say fmt print line com3 now one thing that you can do of course is you can use variatic functions so uh with a variable amount of parameters but that is you know then you need to check okay does this parameter exist does this parameter exist and so on um but as you can see this also works of course we can also dereference it uh but this is a default constructor there you go what we can also do with struct in go is we can add methods to them and not methods like these constructors because those are actually functions we have new computer this is just an independent function which returns a computer pointer what we can do is we can add methods to the actual structs so we can say that there are functions we can call like com3 dot my function for example or my method actually and in order to do that and go we need to specify the object or destruct after the function keyword or after the fun keyword and for this we say for example c and then computer pointer so this is how you do it you say function c computer pointer and then the name of the function for example let's say increase ram and then the parameters here for example amount which is going to be an integer this is how you specify this in go by doing that this c here this computer pointer is going to be the element that you call it on so if i do comp3 dot increase ram which is now a method of the structure this means that comp 3 is becoming or c is becoming that com3 object so whenever i do something with c inside of that function i'm actually working with the object that called this method so what we can do here is we can just go ahead and say c dot ram plus equals amount like that this is a very simple method but we can go ahead and um actually let's let's delete some of that stuff here let's just work with comp one we have this computer here and what we can do is we can print the whole object and then we can say c or comp 1 dot increase ram by 16 more gigs and then we're going to say fmt print line comp 1 and we're going to see that the comp 1 object has changed or the structure instance has changed as you can see we now have 32 gigabytes of ram by just calling this method now we can also make another method or define another method which is going to be also called on computer and this is going to be print information or print info it's not going to take any parameters and we're just going to say okay fmt dot print line we're going to print computer info and then we're going to say fmt printf and we can say manufacturer is going to be a string and it's going to be c dot manufacturer and we can copy that and we can do this for ram it's going to be ram there you go cpu brand is going to be the cpu brand and last but not least we're going to say laptop and actually we're going to have a string here because we're going to say um what was it called string conf i think yeah string font string conf format bool and we're going to format laptop into this here uh what's the problem oh c dot laptop obviously there you go so this is the print info function we can go ahead now and say okay comp1 dot print info then we increase the ram and then we say actually don't need the fmt print line we just need to stick comp one dot print info come on comp one dot print info and that's it so let's see there you go okay we should probably add some backslash ends in the end here so backstage in here back station here accession here and last but not least back station here then this should work there you go you can see we have the print info method and we have the increased ram method so this is how you do uh how you define methods for structs and go so last but not least for today's video i want to talk about interfaces and for this we're going to define an interface up here we're going to call it shape so type shape is going to be an interface and interface basically just tells us which function uh which functions some struct has to implement in order to be off that interface you could say so let's say we have the function area for the shape you can also add stuff like circumference and so on and this area is going to return float 64. so then we're also going to have two structs we're going to have type circle which is going to be a struct and this is going to have um it's going to have a radius which is going to be float 64 as well and we're going to have a rectangle which is going to be a struct and it's going to have a width which is going to be a float 64 and it's going to have height which is going to be a float 64. there you go so what we can now do is we can define a function um or now we don't have the methods or the method area for these structs but when we have this function or method what we can do is we can have one more method which for or function which for example is some function and this function does not take a rectangle it doesn't take a circle as a parameter it takes a shape as a parameter we can do it like that so we can say some shape which is going to be from the interface shape and this basically tells the function that whatever this object is it implements the function area and if we specify more than just one function it implements all these functions so it doesn't matter if it's a rectangle it doesn't matter if it's a circle a triangle whatever it is it implements this particular function or those particular functions specified in the interface so this function some function doesn't need to care about is this a rectangle is this a circle it just calls the functions so let's implement these functions up here we're going to say function called on a circle c area is going to return float 64. and this is going to return circle dot radius times 2 times math dot pi and we need to import math obviously which is done automatically in go land so this is the area of a circle and then we're also going to say okay if it's a rectangle the area function is going to be different it's also going to return float64 but it's going to just return r dot width times r dot height there you go and now we can go ahead for example this is now a very trivial example doesn't make any sense to do it like that but what we can now do is we can go ahead and say fmt print line area of the shape and then we can say fmt dot print line uh shape some shape dot area so if we pass a rectangle we're going to get the area of a rectangle if we pass a circle we're going to get the area of a circle with a different calculation because obviously the formula the formulas are not the same and this goes for all functions that we put in here so for example we can also say print name and we can implement the print name or print description and if we call it on a circle it's going to say hey i'm a circle if we call it on a rectangle it's going to say here i'm a rectangle uh this is how this basically works so let's go down here and create a circle one which is going to be a circle with a radius of uh let's say 23.45 and we're going to have a rectangle rect 1 which is going to be a rectangle it's going to have a width of let's say 87.2 and a height of 22.435 and now we're going to just say sum function circle1 and some function rect1 do we have a problem here area method has a pointer receiver um what did i do different here oh we need to pass the pointer to the rectangle to point it to the to the circle so that should now work as you can see so this gives us the the possibility to be a little bit more dynamic we have a function that we define for all shapes and this works of course for other interfaces as well so you can say interface human and then you have student teacher worker and so on and you can all pass them as a human object as a human interface to some function and then uh you can call the individual methods for these particular structs so that's it for today's video we enjoyed hope you learned something if so let me know by hitting the like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this channel and hit the notification bell to not miss a single future video for free other than that thank you very much for watching see you next video and bye [Music] you

Original Description

In this episode we learn about structs in Go. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This tutorial teaches the basics of structs in Go, including defining and creating structs, adding methods, and implementing interfaces. It provides hands-on examples and code snippets to demonstrate key concepts. By the end of this tutorial, you will be able to define and create structs, add methods, and implement interfaces for dynamic behavior in Go.

Key Takeaways
  1. Define a struct using the `type` keyword and `struct` keyword
  2. Create a struct instance using the `new` keyword and a constructor function
  3. Access struct fields using the dot operator
  4. Use a constructor function to initialize struct fields with default values
  5. Add methods to a struct using the `func` keyword with the struct as a parameter
  6. Implement interfaces for dynamic behavior
💡 In Go, structs are used instead of classes and objects, and can have attributes, properties, functions, and constructors. Implementing interfaces allows for dynamic behavior.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →