► Join my Discord community for free education 👉 discord.com/invite/Ac7CWREe58 ► Exclusive Lessons, Mentorship, And Videos 👉 www.patreon.com/anthonygg_ ► 50% OFF on my Golang course 👉 fulltimegodev.com Thanks for watching
Good explanation. As a note to others still confused, structs are passed by value by default in Go (what Anthony means by copy; it's not the original, remember that) and thus when we create a pointer we have a reference to the memory, which will not be cleared with the function stack.
For anyone looking to better understand Go, I'd recommend implementing OOP in pure C. Structs are essentially wrappers that hold data so you can easily manipulate related information. Methods are just functions with an inferred argument, and access modifiers are just structs that forward method calls to internal structs.
The structs in Go, C, Rust are just the data. In memory there only exists the data. In python and JavaScript each piece of object comes with the data just as the previous language, BUT it also has a bunch of other data that is not what u declared, for example a pointer to its class and the methods. For python for example it even holds onto the methods. 1st type of Language: [an object] - field 1 - field 2 And then somewhere else you have: - function 1 that takes in the type of struct as an argument Whereas the 2nd types of languages: [an object] - field 1 - field 2 - method 1 - method 2 - class metadata ….. This roughly can be what u can imagine the general differences
Anything is procedural underlying. Whole OOP is fake somehow, there are data and data and data and data. Rules of privilege modifications and metaclasses are kinda mix of syntactic sugar and compiler/interpreter rules, which don't allow to compile run something which is completely possible if written in asm or something. Can't access private member? Nothing existing in C. C program usually can get in all memory program get from OS, there is nothing banned. OOP is cannot be done or implemented in asm, it's completely in scope of interpreter/compiler, but everything ends as asm code (or VM bytecode of you want) - but everything at the end, before executing, is machine code or one step before machine code - and there is no way how to do OOP in machine code, it can be only do by higher level filter which dones't allow somethinf what not fit OOP paradigm but in fact it is still doable by machine code and computer itself. So behind everything, from OOP to functional approach, is just a C-like or asm approach - memory and functions. Nothing more.
But if struct has methods attached to it, then every object of that type will have some data about its methods silently embedded by compiler? So it's not like in Go "objects" have only fields while in JS they've also got methods and class metadata... Or am I missing something?
@@adexitum im not sure I understand the question, the structs in Go, Rust, C are only the fields. Since the compiler always knows the type it does not need to embed the methods in the struct itself. if you use interfaces the struct WILL contain extra vtable data to be able to know which method to call. in JS its prototype-based so each object points to the class it belongs to and from there u can figure out which methods it has. but you can also dynamically add and remove methods, especially in python. so the objects are usually alot more bloated due to the dynamic and flexible nature of them
I come from a Python background. When I started learning Go, I found myself constantly comparing its features with Python, which made my understanding a bit difficult. However, this video completely changed my perspective on how I should approach learning Golang.🙇
Thank you for the great explanation! I would just like to add another important distinction between the pointer and the regular function. The scope of the non-pointer function will be within the context of the regular function, whereas the receiver function with a pointer receiver is treated as a method associated with the struct.
Just realized that go slices are also passed by value but the argument still references the same underlying array, so changes to it are reflected on every other slice that references the same underlying array
I am not usually one to wax poetic about programming languages, but this video is really something cool. When you were showing that func (book Book) saveBook() {} is the same as func saveBook(book *Book) {} everything feel into place in my mind
I didn't understand the difference between the two. I am thinking of learning go. Could you please explain what was all that about?
5 месяцев назад
@@adityakiran2956 when you see the * before Book, this means that it's a pointer. A pointer in this case makes the function affect directly the thing passed to it (Book), therefore allowing you to see the changes consistently. Without the *, you would be passing a whole new Book to the function (a copy), changing only this new copy and not getting the expected behavior.
Not just beginners, also senior engineers who never touch Go needs to think differently when writing golang, especially where they coming from OOP lang such as Java/Kotlin, etc
It's also good to compare Go structs with interfaces in JS. Structs are just describing custom data types allowing us to make entities we are comfortable to work with
Now, that is a better explanation. Little nitpicking though, it's Typescript's feature. The interfaces are removed when transpilling TS → JS, as JS has no code structure like that.
I am really proud of you, that you understood the concept of stack and that everything is data in your computer, but I do not personally think it is something extraordinary
Fabulous tip! If I understood it correctly… It reminds me of Python programming when I need to think about dictionaries; on Bash, I think about IFS (word handling via word-splitting).
Well yeah this in go is interesting. Since its just a syntax sugar that means you can write those receiver methods for types you did not make, which is awesome
Great video, comming from ts, the syntax in go is the issue where i find most of my problems while working with go, most of them arising from pointers. thanks for this.
🎯 Key Takeaways for quick navigation: 00:00 🤔 *Thinking in Go requires a different approach for those transitioning from languages like JavaScript, Python, C++, or C#.* 02:37 📦 *In Go, structures are not objects but simple data holders. They encapsulate basic data types like strings, integers, and booleans.* 05:57 ⚙️ *There are only two things you can do with a structure in Go: read data from it and write data into it. Both actions are performed using functions.* 08:37 🔍 *When modifying data in Go, using pointers is crucial to avoid modifying a copy of the structure, ensuring changes persist beyond the function's scope.* 10:44 🧰 *Golang revolves around structures, data, and functions. Understanding this paradigm is essential for effective Go programming.* Made with HARPA AI
My main issue with Go is that pointers overload so many concepts: - Nullable fields use pointers so that you can have nil | something - Mutability is determined (as you point out) by whether I pass a pointer or not - Sidenote here being that if I don't want to write Java style getters all fields need to be exported and therefore mutable by anyone - Passing by reference for optimisation purposes on large structs means passing in a pointer Especially the last thing really screws up the first 2. You might have a nice, non-nullable struct that is safe to pass around but for some reason it grows and now should be a pointer. all safety gets thrown out of the window. Go makes it very challenging to write safe code.
Like Anthony mentioned in a previous video, receivers are simply syntactical sugar for passing the struct to the function as a parameter. Whether that be a pointer or not. But, the go idiomatic way is definitely receivers. Lends to better readability.
Hi. Excellent points to know about this fantastic language. The go-way declaration of functions binded to structs (like methods), naturally return one "instance" of object. Filled with the info that you send to it: type Book struct { title string numPages int } func (b Book) saveBook() { // just to do something fmt.Println(b) } func main() { book := Book{ title: "A comeback without a departure", numPages: 1, } book.saveBook() } The exit is: == go run . {The return of those who were not 1} My point is: Its not the same? Why should we use pointers here if the go-way do the same behavior? Thanks in advance!
When I first started learning golang I was absolutely flabbergasted that there was no concept of class inheritance. Really had get on-board with composition.
Objects are objects, they expose behavior. Data is data. It doesn't matter which language you write. I recommend for you to look at domain driven design to distinguish them better.
that's true of most oop languages, they pass the "this" pointer in every method signature under the hood. only difference is that the methods are mapped directly to the type's instance. Most languages actually do something closer to what go does (as compared to the mainstream oop languages named). Sadly go lacks some extremely useful type constructs like tagged unions and is very naive in his type design.
To add more to this, most oop languages a class could have a “hidden” vtable pointer for any methods that are overridden by the derived class. Since go doesnt allow inheritance this doesnt exist. Simply put: Go struct is a “class” without inheritance and which allow you to specify read only methods.
I love this C approach. Doing everything manually. You can fully make OOP in C, with only one reason - when you try something like access private member from outside, compiler/interpreter of OOP language doesn't allow it. C allows it. So private loses its sense. But all things like constructor, inheritance, polymorphism and stuff, it can be all simulated in C - and even OOP languages compile into byte/machine code with machine/procedural approach, with a boilerplate and bloat of helping tables and tables and tables and tables... and whole stuff made just to make classes working. But it's just only a layer of abstraction, nothing more.
I kinda feel it was helpful for me to have learned C language very early in my programming journey. I can understand why folks who started with other languages might have difficulty grasping GO language.
I am working on Golang for 1 year and now I know that my understanding was totally wrong....one of the most required Golang videos if you are working on already written Go code. Thanks @Anthony GG
Take my subscription mate. I am starting with Go. I hope that this language will help me get out of the box of the OOP models entities etc and see the real code/architecture behind it. I feel in trap with MVC Laravel. I feel that I need to escape from this approach and go to something new. Hope the best.
This is the same in Go, except that "structs" belong to the "value types", if you want to call them that. slices, maps, channels, pointers and functions would then be what is commonly called a "reference type" so you dont really have to worry about pointers with those.
Nothing is passed by value in Python, the whole data model is referencial. If you need a copy, you have to directly use copy() or deepcopy() functions.
Interfaces threw me off coming from typescript and a little python. Best thing that worked from me was just writing an app that needed them. Then I was like ooooooooh ya I see. This knowledge makes understanding things so much better
Arguably it makes sense to also explain why you would use one over the other if they are the same. It does not make sense to call the other function "saveBook". Since it has a namespace it makes sense to call it "save". People coming from C know the pain of adding pseudo namespace to functions. And the joy of explaining to a beginner that all these books are different things "function saveBook( book *Book)" Very often what people like about object oriented programming are not mainly object themselves, but the syntax. Even some functional languages (.e.g Elixir) have adopted some kind of postfix notation because it represents the flow of data transformation from left to right. e.g. "books.first.title.toUppercase"
After learning a little bit of C++ all I can say is: Looks OOP enough to me LOL The "OOP looking" function at the top is just like the syntax for methods in C++, but I can write it as the function below, because C++ got that thanks to C. In that regard, for C and C++ devs Go feels more familiar than other high-level languages.
A lot of your explanations makes sense and I can agree. Coming from Java (especially Spring Boot 😒 ) and coding in Go for about 2,5 years now I am a bit confused. Lets assume you would save the book from your example in a database (for example a MongoDB or Postgres). My approach is to create a BookRepositoryInterface and a BookRepository which of course implements the interface. The Repository would have a save(book *Book) function. The database client would be set as a field in the repository (simple dependency injection). Of course this is simply imitating the practices from Java in Go, but I haven't found a better way till now. How would you achieve a "real" save to a database with your approach? I think it is a little bit abstract without a real world example. You need a client which manages the database communication and preferable you want only one and don't create new connections for every instance of the book struct so you would not loose performance.
I haven't touched Golang yet... but It seems the man of the video is being dogmatic. He talks about syntactic sugar as it should be prohibited... all high level language ARE SYNTACTIC SUGAR. And when talking about testing... how would you mock for unit testing... or you don't unit test... This man is crazy... Tomorrow I will take Golang to start learning, but I have seen other opinions opposed to the one presented here... For this man Clean Architecture would be shit
@@maximilianosorich554 Not to be rude, but I think you didn't understand the video if you think he's making a point about (let alone against) syntactic sugar. He's merely explaining the difference between passing by reference vs. passing by value, which is something you don't usually have to think about in the higher level oop languages he mentioned.
Please don't be mad cause I'm learning Go currently. But does pointers replace Classes? like for pointer it points to the original "Book" and a class you can point to the original "Book" or make a copy of it?
This is pretty much like C# with the only difference that it seems that Go is using value types by default. For example "class" in C# is reference type, while there is still "struct" which is value type. Also I'm not sure how Go exactly deals with concurrency, because the way you are showing how to modify the "Book" by it's pointer can cause concurrency issues in C#. Better approach IMO is to create a new "Book" and return it and not mutate the state of the existing "Book" (I'm sure you know it, but I wonder if this paradigm is the same in GoLang). Also in C# we now have "record" which allows us to mutate only the parts we want from an existing object and return a completely new one with copied values.
In the "good old days" the Golang approach would be called OBP ("object based approach/programming"-> encapsulation & abstraction) in contrary to the today's OOP ("object oriented approach/programming "-> encapsulation, abstraction + inheritance+ polymorphism). In OBP the focus is more in the interaction between object's than the taxonomy of objects into classes and class hierarchies. Unfortunately most programmers today a raise into OOP-thinking than understand first the OBP-thinking which is more fundamental and more near to the machine.
While its a good explaination i find it important for go coders to understand when its the right approach (many cases) and when its the better approach or lets say the more fitting with package scoped variables. If your working in a single instance, lets say your core component, you probably dont need a core factory since your application is running with one singular core. therefor using an object oriented approach for this package would be an uneccessary overhead and therefor should not be done. I just add this because i see alot of go projects especially new ones which tend to 'over oop' everything just for the sake off. You need to balance it out based on your needs. Btw great video .)
Basically, we are going to have to think more in terms of the memory(pointers, etc.) and not only values. Does this approach have any benefit to offer other than just making the writing and reading part easy when working with struct(or data structure)?
> think more in terms of the memory Not necessary. Go is garbage collected, and so you can code like you do in JavaScript or Python until you are ready for pointers. I am starting out with Go and I apply the same rules as JavaScript: Simply copy values of primitives / literals (int, float, bool, byte...) and for something bigger I use pointers & references (structures, slices, maps...) I really like the explanation of pointers here: ruclips.net/video/sTFJtxJXkaY/видео.html
Thanks for the video! I'd like to say, that methods aren't exactly a syntactic sugar. They add methods, which modifies the type info, as could be seen from the reflection. Regardless of that, adding a save method to a model isn't nice in any language, not just Go - we don't know how this book is gonna be serialized. Serialization should be either a function, or a method of a specific book serializer, but definitely not of the book. Models have to stay models in any language.
SaveBook is just a random name I came up with to be honest. You need to understand that explaining things to new people is an art on itself, they need to make connections inside their mind. Using these names and other simple explanations really helps them to get a better grasp of the matter. Once they get better they will do their own due diligence to see that certain terms have a more deeper underlying meaning.
Uh, I understand! I like your vids - I'm amending, not criticizing. I don't feel empowered to criticize creations. But I feel like adding my 5 cents if I have something to add (-;
This not only applies to Go. When you learn a new programming language, you'll have to think in a new way. Sticking to traditional OOP or FP is fine, but then you'll gonna miss the real benefits of that language. Programming paradigm and patterns are just concept. They are not a master key.
Well, the same applies to other languages really. Receiver functions and class methods in any language are _also_ just syntactic sugar, with varying degrees of abstraction and complexity...
Oh you bet I'm sharing this with my non-Golang friends who come to try out the language and express how weird Golang looks and feels in companrison to Java/C#.
What advice would you have for people who have just graduated and have not worked in any software yet, but who choose Golang as their first language, having already some programming basics, but at university where Golang was not taught?
Hi @anthonygg_, Can we mutate the data in the structs without encapsulation ? by making the fields public without writing func with pointers to the struct ? It is a good approach to use a global state shared in the app ?
How is sending pointer receiver different or worse than sending a pointer function argument? Main thing I understand is that to pass the pointer if you want to update original data in the function.
I fail to understand what are the advantages or disadvantages between the first and second function implementation. They are declared differently but act the same no?
► Join my Discord community for free education 👉 discord.com/invite/Ac7CWREe58
► Exclusive Lessons, Mentorship, And Videos 👉 www.patreon.com/anthonygg_
► 50% OFF on my Golang course 👉 fulltimegodev.com
Thanks for watching
Short explanation: It's like C
C, but easy
Exactly that!
Good explanation. As a note to others still confused, structs are passed by value by default in Go (what Anthony means by copy; it's not the original, remember that) and thus when we create a pointer we have a reference to the memory, which will not be cleared with the function stack.
Thanks. 100% correct
When he said that I immediately thought if Go does that by default. Thanks for clearing that up.
Go passes everything by value, not just structs
@@yegorzakharov8514 so does C#, but some of its types are essentially pointers by default, so that’s what you’re copying as a parameter.
@@yegorzakharov8514yeah but sometimes the “data” being passed contains a pointer
Dude… thank you so much for this, cause I literally asked you about this yesterday and today you have a video on it. God bless man!
Thank you!
For anyone looking to better understand Go, I'd recommend implementing OOP in pure C. Structs are essentially wrappers that hold data so you can easily manipulate related information. Methods are just functions with an inferred argument, and access modifiers are just structs that forward method calls to internal structs.
Where 'this' is the default argument.
The structs in Go, C, Rust are just the data. In memory there only exists the data.
In python and JavaScript each piece of object comes with the data just as the previous language, BUT it also has a bunch of other data that is not what u declared, for example a pointer to its class and the methods. For python for example it even holds onto the methods.
1st type of Language:
[an object]
- field 1
- field 2
And then somewhere else you have:
- function 1 that takes in the type of struct as an argument
Whereas the 2nd types of languages:
[an object]
- field 1
- field 2
- method 1
- method 2
- class metadata
…..
This roughly can be what u can imagine the general differences
Thanks for the detailed amend
Cool explanation. Coming (and still mostly coding in) JS and Python, I'm loving Go's approach
Anything is procedural underlying. Whole OOP is fake somehow, there are data and data and data and data. Rules of privilege modifications and metaclasses are kinda mix of syntactic sugar and compiler/interpreter rules, which don't allow to compile run something which is completely possible if written in asm or something.
Can't access private member? Nothing existing in C. C program usually can get in all memory program get from OS, there is nothing banned.
OOP is cannot be done or implemented in asm, it's completely in scope of interpreter/compiler, but everything ends as asm code (or VM bytecode of you want) - but everything at the end, before executing, is machine code or one step before machine code - and there is no way how to do OOP in machine code, it can be only do by higher level filter which dones't allow somethinf what not fit OOP paradigm but in fact it is still doable by machine code and computer itself.
So behind everything, from OOP to functional approach, is just a C-like or asm approach - memory and functions. Nothing more.
But if struct has methods attached to it, then every object of that type will have some data about its methods silently embedded by compiler? So it's not like in Go "objects" have only fields while in JS they've also got methods and class metadata... Or am I missing something?
@@adexitum im not sure I understand the question, the structs in Go, Rust, C are only the fields. Since the compiler always knows the type it does not need to embed the methods in the struct itself. if you use interfaces the struct WILL contain extra vtable data to be able to know which method to call.
in JS its prototype-based so each object points to the class it belongs to and from there u can figure out which methods it has. but you can also dynamically add and remove methods, especially in python. so the objects are usually alot more bloated due to the dynamic and flexible nature of them
I come from a Python background. When I started learning Go, I found myself constantly comparing its features with Python, which made my understanding a bit difficult. However, this video completely changed my perspective on how I should approach learning Golang.🙇
I don't have a py background, but also compared it to py :D
Wish this video existed when I first started writing Go. Really well done and easy to understand for OOP programmers starting Go!
same words, accepted the Go way long ago, but the "syntax sugar" example made things connect in my head better
How does he move the cursor quickly up and down while typing ?
it looks like he is using vim movement.@@avonflex5031
@@avonflex5031 vim
@@avonflex5031, it is called VIM motions.
One thing that I like about hanging functions off of structs is that code bases are far more discoverable via lsp
yeah dont take the advise of this youtuber, seems dumb advice tbh
This was the first in a series of big breakthroughs for me using GO. Thank you, Anthony!
Thanks for the video. Took me a couple mins to realize its "classes", not "clauses" :)
I struggled to understand pointers and your explanation was mind opening. Kudos.
Just fumbled around about this topic and the algorithm bless me with this vid. Thanks!
🤩
I saw a comment saying interfaces, i think you should show when to use interfaces and methods. Good video.
This channel is a gem - binging all your videos as a Go learner
Good luck my man
Thanks man, I've started learning Go (coming from C#, C and Python) and this video just unlocked my light bulb moment
Happy I could help out. You will do great coming from those languages.
Thank you for the great explanation! I would just like to add another important distinction between the pointer and the regular function. The scope of the non-pointer function will be within the context of the regular function, whereas the receiver function with a pointer receiver is treated as a method associated with the struct.
Beautiful video. Thanks for the hints on pointers, I should really study these more
Thank you! This kind of information is what i need to know whenever I'm about to start learning a new programming language.
Just realized that go slices are also passed by value but the argument still references the same underlying array, so changes to it are reflected on every other slice that references the same underlying array
I am not usually one to wax poetic about programming languages, but this video is really something cool. When you were showing that func (book Book) saveBook() {} is the same as func saveBook(book *Book) {} everything feel into place in my mind
I didn't understand the difference between the two. I am thinking of learning go. Could you please explain what was all that about?
@@adityakiran2956 when you see the * before Book, this means that it's a pointer. A pointer in this case makes the function affect directly the thing passed to it (Book), therefore allowing you to see the changes consistently. Without the *, you would be passing a whole new Book to the function (a copy), changing only this new copy and not getting the expected behavior.
As soon as he said "YavaScript" I knew he was gonna cook 🔥
as someone who's just starting to learn go, this man's channel is a gem
Not just beginners, also senior engineers who never touch Go needs to think differently when writing golang, especially where they coming from OOP lang such as Java/Kotlin, etc
10:31 "Golang is _only_ about Structures, Data and Functions. That's the only thing you need to know." ❤
This is very importand fundamental concept that we should to know and not break using approaches from other languages. Keep it simple!
Excellent video for anyone going from Python to Go, less helpful for C to Go, but still great reminder
It's also good to compare Go structs with interfaces in JS.
Structs are just describing custom data types allowing us to make entities we are comfortable to work with
Now, that is a better explanation.
Little nitpicking though, it's Typescript's feature.
The interfaces are removed when transpilling TS → JS, as JS has no code structure like that.
😢 😢😢
Your examples made my confusions alot clear, ty alot
I am really proud of you, that you understood the concept of stack and that everything is data in your computer, but I do not personally think it is something extraordinary
Fabulous tip! If I understood it correctly… It reminds me of Python programming when I need to think about dictionaries; on Bash, I think about IFS (word handling via word-splitting).
Well yeah this in go is interesting. Since its just a syntax sugar that means you can write those receiver methods for types you did not make, which is awesome
I enjoyed the way you explained for better understanding. Thanks!!
Clean and direct, thank you very much.
I realy learned alot from you thank you so much! keep up the good work!
Great explainer video!! Keep up the good work!!
Great video, comming from ts, the syntax in go is the issue where i find most of my problems while working with go, most of them arising from pointers. thanks for this.
Loved it, you cleared it up pretty well! Kudos to you!
This was a great explanation for me to understand things better.
🎯 Key Takeaways for quick navigation:
00:00 🤔 *Thinking in Go requires a different approach for those transitioning from languages like JavaScript, Python, C++, or C#.*
02:37 📦 *In Go, structures are not objects but simple data holders. They encapsulate basic data types like strings, integers, and booleans.*
05:57 ⚙️ *There are only two things you can do with a structure in Go: read data from it and write data into it. Both actions are performed using functions.*
08:37 🔍 *When modifying data in Go, using pointers is crucial to avoid modifying a copy of the structure, ensuring changes persist beyond the function's scope.*
10:44 🧰 *Golang revolves around structures, data, and functions. Understanding this paradigm is essential for effective Go programming.*
Made with HARPA AI
My main issue with Go is that pointers overload so many concepts:
- Nullable fields use pointers so that you can have nil | something
- Mutability is determined (as you point out) by whether I pass a pointer or not
- Sidenote here being that if I don't want to write Java style getters all fields need to be exported and therefore mutable by anyone
- Passing by reference for optimisation purposes on large structs means passing in a pointer
Especially the last thing really screws up the first 2. You might have a nice, non-nullable struct that is safe to pass around but for some reason it grows and now should be a pointer. all safety gets thrown out of the window. Go makes it very challenging to write safe code.
Minor issue: Go uses "nil" instead of more sane "null" (if only I could get a nickel for every time I type null instead of nil. )
I am coming from PHP so these concepts feel really at home for me. Starting to learn Go and excited to see i am getting it from the start
So, what is the common GO way of manipulating structs? Or is it just a personal preference whether a function or method is used?
U should use the Go method receivers. But I wanted to show that changing the syntax could give newcomers a better understanding whats going on
Like Anthony mentioned in a previous video, receivers are simply syntactical sugar for passing the struct to the function as a parameter. Whether that be a pointer or not. But, the go idiomatic way is definitely receivers. Lends to better readability.
gotcha, thank you
What is the VS Code Theme you are using?
Gruvbox
@@anthonygg_ thank you
for a moment i thought 'The Rock' was teaching golang, good stuff though !
Hi. Excellent points to know about this fantastic language.
The go-way declaration of functions binded to structs (like methods), naturally return one "instance" of object. Filled with the info that you send to it:
type Book struct {
title string
numPages int
}
func (b Book) saveBook() {
// just to do something
fmt.Println(b)
}
func main() {
book := Book{
title: "A comeback without a departure",
numPages: 1,
}
book.saveBook()
}
The exit is:
== go run .
{The return of those who were not 1}
My point is: Its not the same?
Why should we use pointers here if the go-way do the same behavior?
Thanks in advance!
When I first started learning golang I was absolutely flabbergasted that there was no concept of class inheritance. Really had get on-board with composition.
Objects are objects, they expose behavior. Data is data. It doesn't matter which language you write. I recommend for you to look at domain driven design to distinguish them better.
that's true of most oop languages, they pass the "this" pointer in every method signature under the hood. only difference is that the methods are mapped directly to the type's instance. Most languages actually do something closer to what go does (as compared to the mainstream oop languages named). Sadly go lacks some extremely useful type constructs like tagged unions and is very naive in his type design.
To add more to this, most oop languages a class could have a “hidden” vtable pointer for any methods that are overridden by the derived class. Since go doesnt allow inheritance this doesnt exist.
Simply put: Go struct is a “class” without inheritance and which allow you to specify read only methods.
I love this C approach. Doing everything manually. You can fully make OOP in C, with only one reason - when you try something like access private member from outside, compiler/interpreter of OOP language doesn't allow it. C allows it. So private loses its sense.
But all things like constructor, inheritance, polymorphism and stuff, it can be all simulated in C - and even OOP languages compile into byte/machine code with machine/procedural approach, with a boilerplate and bloat of helping tables and tables and tables and tables... and whole stuff made just to make classes working. But it's just only a layer of abstraction, nothing more.
thanks a log it was really good
if I'm not wrong, I visualized the struct as a columns in a table with different data types and you use functions to insert data .
I kinda feel it was helpful for me to have learned C language very early in my programming journey. I can understand why folks who started with other languages might have difficulty grasping GO language.
very great explanation! i was a bit confused because i always compared to OOP and never made any sense xd
Thank you
Go is actually more like C than anything else. Except 1000 times better!
Brother .....❤ more videos this simple and bird eye view teaching ...
This video was very revealing.
Thanks a lot for the video!!!!
I am working on Golang for 1 year and now I know that my understanding was totally wrong....one of the most required Golang videos if you are working on already written Go code. Thanks @Anthony GG
If you want to master Go, learn from its direct ascendent: Oberon. But, great points you brought.
Brilliant explainer! Thanks.
Take my subscription mate. I am starting with Go. I hope that this language will help me get out of the box of the OOP models entities etc and see the real code/architecture behind it. I feel in trap with MVC Laravel. I feel that I need to escape from this approach and go to something new. Hope the best.
yes in JS and PY primitive data types are passed by value & non primitives are passed by reference automatically, one dont need to specify anything
This is the same in Go, except that "structs" belong to the "value types", if you want to call them that. slices, maps, channels, pointers and functions would then be what is commonly called a "reference type" so you dont really have to worry about pointers with those.
Nothing is passed by value in Python, the whole data model is referencial. If you need a copy, you have to directly use copy() or deepcopy() functions.
02:25 You meant we should see structs... as a "structure" of data? lol
Jokes aside, great video Anthony ❤
By adding methods to the structure, it can satisfy some interface else it is just plain data.
even if it doesnt have methods it can still satisfy an interface, if said interface doesnt have methods
Interfaces threw me off coming from typescript and a little python.
Best thing that worked from me was just writing an app that needed them. Then I was like ooooooooh ya I see.
This knowledge makes understanding things so much better
Arguably it makes sense to also explain why you would use one over the other if they are the same. It does not make sense to call the other function "saveBook". Since it has a namespace it makes sense to call it "save". People coming from C know the pain of adding pseudo namespace to functions. And the joy of explaining to a beginner that all these books are different things "function saveBook( book *Book)"
Very often what people like about object oriented programming are not mainly object themselves, but the syntax. Even some functional languages (.e.g Elixir) have adopted some kind of postfix notation because it represents the flow of data transformation from left to right. e.g. "books.first.title.toUppercase"
Thank you for sharing!
When I know it is just syntactic sugar, it makes much more sense 😊
Structs seem very similar to C/C++, or Cobol, or Fortran in their usage. Is that true?
After learning a little bit of C++ all I can say is: Looks OOP enough to me LOL
The "OOP looking" function at the top is just like the syntax for methods in C++, but I can write it as the function below, because C++ got that thanks to C.
In that regard, for C and C++ devs Go feels more familiar than other high-level languages.
A lot of your explanations makes sense and I can agree. Coming from Java (especially Spring Boot 😒 ) and coding in Go for about 2,5 years now I am a bit confused.
Lets assume you would save the book from your example in a database (for example a MongoDB or Postgres).
My approach is to create a BookRepositoryInterface and a BookRepository which of course implements the interface.
The Repository would have a save(book *Book) function. The database client would be set as a field in the repository (simple dependency injection). Of course this is simply imitating the practices from Java in Go, but I haven't found a better way till now.
How would you achieve a "real" save to a database with your approach? I think it is a little bit abstract without a real world example.
You need a client which manages the database communication and preferable you want only one and don't create new connections for every instance of the book struct so you would not loose performance.
I haven't touched Golang yet... but It seems the man of the video is being dogmatic. He talks about syntactic sugar as it should be prohibited... all high level language ARE SYNTACTIC SUGAR. And when talking about testing... how would you mock for unit testing... or you don't unit test... This man is crazy... Tomorrow I will take Golang to start learning, but I have seen other opinions opposed to the one presented here... For this man Clean Architecture would be shit
@@maximilianosorich554 Not to be rude, but I think you didn't understand the video if you think he's making a point about (let alone against) syntactic sugar. He's merely explaining the difference between passing by reference vs. passing by value, which is something you don't usually have to think about in the higher level oop languages he mentioned.
Please don't be mad cause I'm learning Go currently. But does pointers replace Classes? like for pointer it points to the original "Book" and a class you can point to the original "Book" or make a copy of it?
Why would I be mad? 😊. No pointers do not replace classes. Pointers allow you to update memory directly.
This is pretty much like C# with the only difference that it seems that Go is using value types by default. For example "class" in C# is reference type, while there is still "struct" which is value type. Also I'm not sure how Go exactly deals with concurrency, because the way you are showing how to modify the "Book" by it's pointer can cause concurrency issues in C#. Better approach IMO is to create a new "Book" and return it and not mutate the state of the existing "Book" (I'm sure you know it, but I wonder if this paradigm is the same in GoLang). Also in C# we now have "record" which allows us to mutate only the parts we want from an existing object and return a completely new one with copied values.
Pointers are always NOT safe for concurrent usage. Thats where channels come into play.
Thank you @@anthonygg_ . I'm kind of new to Go and I still don't know all of its capabilities. Will read what "channels" are.Thanks!
In the "good old days" the Golang approach would be called OBP ("object based approach/programming"-> encapsulation & abstraction) in contrary to the today's OOP ("object oriented approach/programming "-> encapsulation, abstraction + inheritance+ polymorphism). In OBP the focus is more in the interaction between object's than the taxonomy of objects into classes and class hierarchies. Unfortunately most programmers today a raise into OOP-thinking than understand first the OBP-thinking which is more fundamental and more near to the machine.
damn thank you so much sir! i am not learning go the better way
Good video. Can you do interfaces?
YavaScript!
THANK YOU, FFFF THANK YOU
Anthony, what;s your vscode theme?
hi Anthony, what is the colorscheme u are using in the video?
Gruvbox the hard contrast one
While its a good explaination i find it important for go coders to understand when its the right approach (many cases) and when its the better approach or lets say the more fitting with package scoped variables. If your working in a single instance, lets say your core component, you probably dont need a core factory since your application is running with one singular core. therefor using an object oriented approach for this package would be an uneccessary overhead and therefor should not be done.
I just add this because i see alot of go projects especially new ones which tend to 'over oop' everything just for the sake off. You need to balance it out based on your needs.
Btw great video .)
Good explanation, however, you missed showing how the two variations of the func are called.
True. But I have several videos covering this aswel. This video was a specific exercise taking a step back
Basically, we are going to have to think more in terms of the memory(pointers, etc.) and not only values. Does this approach have any benefit to offer other than just making the writing and reading part easy when working with struct(or data structure)?
> think more in terms of the memory
Not necessary. Go is garbage collected, and so you can code like you do in JavaScript or Python until you are ready for pointers. I am starting out with Go and I apply the same rules as JavaScript: Simply copy values of primitives / literals (int, float, bool, byte...) and for something bigger I use pointers & references (structures, slices, maps...)
I really like the explanation of pointers here:
ruclips.net/video/sTFJtxJXkaY/видео.html
Thanks for the video! I'd like to say, that methods aren't exactly a syntactic sugar. They add methods, which modifies the type info, as could be seen from the reflection.
Regardless of that, adding a save method to a model isn't nice in any language, not just Go - we don't know how this book is gonna be serialized. Serialization should be either a function, or a method of a specific book serializer, but definitely not of the book. Models have to stay models in any language.
SaveBook is just a random name I came up with to be honest. You need to understand that explaining things to new people is an art on itself, they need to make connections inside their mind. Using these names and other simple explanations really helps them to get a better grasp of the matter. Once they get better they will do their own due diligence to see that certain terms have a more deeper underlying meaning.
Uh, I understand! I like your vids - I'm amending, not criticizing. I don't feel empowered to criticize creations. But I feel like adding my 5 cents if I have something to add (-;
@@yarcat I agree with you dont get me wrong. There a lot of things wrong with saveBook 😅.
4/10 didn't roll is Rs every single opportunity he had.
(great vid btw)
Really good information
i never used golang... but now i see the hype around it.. it's just like a good old C but easier...
Jup. You got it.
This not only applies to Go. When you learn a new programming language, you'll have to think in a new way. Sticking to traditional OOP or FP is fine, but then you'll gonna miss the real benefits of that language. Programming paradigm and patterns are just concept. They are not a master key.
Well, the same applies to other languages really. Receiver functions and class methods in any language are _also_ just syntactic sugar, with varying degrees of abstraction and complexity...
Good explanation. Method definitions perhaps are a bit more than syntactic sugar e.g. code organization for composition (interfaces).
Oh you bet I'm sharing this with my non-Golang friends who come to try out the language and express how weird Golang looks and feels in companrison to Java/C#.
What advice would you have for people who have just graduated and have not worked in any software yet, but who choose Golang as their first language, having already some programming basics, but at university where Golang was not taught?
Hi @anthonygg_, Can we mutate the data in the structs without encapsulation ? by making the fields public without writing func with pointers to the struct ? It is a good approach to use a global state shared in the app ?
Thnak you for your content! Always useful videos. Keep up the good work! 🚀
You really made things so much clearer. Thanks Dude keep up the good work 👍💯✨
What extension/config are you using to emulate Vim modal editing within VSCode?
Default VIM plugin that comes with VSCODE
@@anthonygg_thx a lot! Very useful content❤
How is sending pointer receiver different or worse than sending a pointer function argument?
Main thing I understand is that to pass the pointer if you want to update original data in the function.
No difference.
amazing explanation
I fail to understand what are the advantages or disadvantages between the first and second function implementation. They are declared differently but act the same no?
Yes. They behave the same.
I thought you switched to neovim? What made you go back to vscode?