Everything You Need To Know About Pointers In Golang
Vložit
- čas přidán 25. 11. 2022
- ► Join my Discord community for free education 👉 / discord
► Become a Patreon for exclusive tutorials 👉 / anthonygg_
► Follow me on Twitter 👉 / anthdm
► Follow me on GitHub 👉 github.com/anthdm
In this Golang tutorial, I will teach you everything you need to know about pointers in Golang. When to use them, and the most common pitfalls new developers will run into.
#golang
► Join my Discord community for free education 👉 discord.com/invite/bDy8t4b3Rz
► Become a Patreon for exclusive tutorials 👉 www.patreon.com/anthonygg_
To be precise. A pointer is not really an integer cause it cannot be negative. It is an "address" that points to a specific slot in memory. My excuses for using the word "integer" in this video.
Thanks for watching
there are unsigned integers
It actually shows how intelligent someone is, when they can explain something to you in a very simple way, that's what this guy does. Thanks Anthony!
Thank you very much!
thanks for the great video!
a couple of points regarding pointers, perhaps it will be useful to someone.
1. Pointers allow you to bypass the copying of a variable, what allows you to save memory, as well as change the object by reference without copying it (this was already mentioned in the video)
2. The pointer value can be nil (var myPointer *int), so it is very convenient to use it, for example, where we return an object from the database, but under certain conditions the object may not be found in the database (the classic example is ORM):
type UserID int
type User struct {
userId UserID
firstName string
lastName string
}
func FindUser(id UserID) *User {
var userId UserId = 123
if id == userId {
return &User{
userId: userId
firstName: "First Name",
lastName: "Last Name",
}
}
return nil
}
func main() {
if user := FindUser(UserID(123)); user != nil {
fmt.Println(user.firstName + " " + user.lastName)
}
}
3. Sometimes it is convenient to create a pointer to a particular type with a default value that matches that type. To do this, you can use the "new" function, which returns a pointer to an initialized object in memory with a default value:
{
var myPointer *int // myPointer is nil
}
{
myPointer := new(int) // myPointer is an address to an integer type with value 0
}
You need to be careful by using pointers, because the uncontrolled use of pointers puts a load on the garbage collector.
one more thing regarding of pointers to reference types (map, chan, slice). it makes no sense to create pointers to them when passing them as an argument to a function in the hope of saving memory, since their structures already contain a pointer, so creating their copies does not lead to large memory costs.
Wish I could hit the like button twice on this! Thanks man.
Thank you!
I will hit 3 time
Man that’s a good video, hands on examples are always the key for me to understand something entirely.
Thanks 🙏🏼
Catching up on some of your videos today, great one again!
Thanks a lot! This video did it for me!
I understood pointer’s theoretically, but learning them in context is really helpful!
It also helped me understanding methods in Go, they can be a bit confusing!
Thanks 😊
Great video. Super big thanks!
thanks for such detailed explanation!
Very informative video
this helps me to understand the concept very clearly
Thanks
thank you so much! this is a very good explainer on a formally very confusing subject in Go for me
Best youtube channel for golang till now awesome 🎉❤
There is joy in just hearing him speak 🥰🥰
Thanks I really like your explanation about pointers in GO
The Goat teacher 🤞
amazing! really helpful👍
Clean cut explanation
good job man, very well explained
Thanks!
Wow I've been looking for an explanation like this, being new to a language that heavily uses pointers.
pointers should not be used often unless absolutely necessary. Pass by value makes a lot of sense to limit accidental pointer mutation.
perfect! thank you.
Subscribed instantly!
🙏
awesome video
Mate, thank you. I'm new to golang, coming from python. Even though the concept is clear itself with all them referencing to addresses in memory, the example with DB made the most sense to me lol.
And offtop:
I reckon u r Scottish, right? Ur accent made me writing this comment. I absolutely enjoyed it. You r trying so hard to not to swallow half of the letters and sounds they represent lol. So cute. I can't :)) Thank you. I had double pleasure listening to u.
P.S. Don't consider it offensive or sth, I'm Ukrainian, so for me them things r nothing except amusing and endearing, representing your own culture, which I respect (and enjoyed).
he is Italian
thank you GSP
Useful, undrestanble.
thanks mate, how you jump to previous line position after typing something in vim ? like you type “type” and jumped into previous line and typed “Player” and jumped again to previous line😊
Not saying that what you're saying isn't true, but I do find it humorous that on practically every tech-related video out there that host will say "a lot of people are commenting/asking" about (whatever issues is being talked about in video) as a sort of appeal to the masses :D
True, I told myself to avoid that as much as possible. But you caught me here.
Im curious what are your thoughts about adding nil checks at the beginning of functions that use pointers or pointer receivers?
My pov is that it adds "necessary"(i say this loosely) code to your functions as its a time saver when avoiding with panics, although IMO the go complier panic does point you to where the nil deref did happen in the stack trace, so nil checks kind of are nice but not really necessary, just as you said, with great power comes great responsibility. im curious on your stance what i mean if im not clear is
if fooStructPointer == nil {}
Well. It depends. Only if you know it might be nil, cause it can be nil
Nice example, I am coming from TS world where you have no such pointers and you would just put result from function into a new variable. This is really nice feature in Go.
Thank you for the good, practical lesson about pointers! Two thoughts: 1) Your final recommendation was, only use pointers when you really need it. One reason you explicitly mentioned was „the object is very big“. But the more obvious one might be „some changes need to be made on the object“ - might be a good criteria for those who are unsure. 2) I am not sure, but I imagine that Golang has a „copy on write“ concept (a struct as a parameter is not copied physically unless it is changed - this could be decided roughly at compile time and exactly at runtime). If this would be the case, „chages need not be made“ would be the only case for using a reference (pointer). - I guess a little test programm like your example with the „bigdata“ func coud show, if memory cunsumption grows even if the func has no statement writing on the bigdata-struct. - Or do you already know if Golang has this sort of optimization?
To be honest I don't really have a clue :). Like you said, maybe some material for exploration in code.
Thanks for this detailed explanation, i just want to know what vscode theme are you using??
Gruvbox
@@anthonygg_ thanks, hoping for more Go tutorials like this ❤️
@anthonygg_, can you tell me what VS Code theme you have been using?
Gruvbox
great video. What I found however is that I was creating a struct for the program's configuration, every function in the program used the struct, so every function had "func (conf *Conf) DoSomething()" -- Instead of doing that, is it bad to just declare conf as a global variable? Are global variables bad?
Well depends, globals have there usecase sometimes
Hey @Antony if you see this comment: I have a doubt: when you pass a pointer, it’s passing the very pointer to the stack as in C language? Or a copy of the pointer that is pointing to the same memory area? Because if it’s the second option, this will require a garbage collection right?
I think everything is a copy in golang. Same goes for passing pointers
Hey @Anthony - do you have a video on how you use VS Code?
Will make one tomorrow
@@anthonygg_ wow! thats awesome! I like the way you don't need a mouse. and how you move between tabs, terminal..
Anthony, what theme do u use in vscode?
Gruvbox
@@anthonygg_ thanks
❤
GoLang is really confusing in the way how it treats inside the function parameters passed by value - it's always a copy! But then if it's a struct - modifications inside the function won't be visible outside (as your local changes are lost). If it's a slice - you can modify existing elements but if slice capacity changes, it will be lost (as inside the function you have only a copy of slice signature with pointers to the data, length and capacity). Similarly in maps... To get it right, you need deep understanding how data around struct, map, slice is organised and what is actually passed by value.
Why Go/The IDE does not check the type of Player as nil before letting it execute and return the nil pointer error?
Hmm good question will take a dive
I use pointers when nil has a meaning other than the empty struct value. Not so often, but, is it an anti-pattern?
I do the same, but its not always the best option. But its easy to compare against
As a c/c++ its fell like home 😊
What's the difference between func and methods ?
Go has no methods. Function receivers are syntactic sugar
Really don't like this guy's attitude but the content is gold - this was an awesome explanation haha 🤡
The king does whatever the fuck he wants. But thanks ❤️
The league of extra ordinary developers!
Teemo top
Or feed
@@anthonygg_ 😂Fiora top or Jax
@@tintin537 Be ready. Xmass holidays we gaming LIVE on stream. Do NOT let me down. Hence, carry me.
@@anthonygg_ I play on eune servers what server do you play on?
never thought I would be learning programming from Johnny Sins himself
I can learn you some other stuff also 😂
@@anthonygg_ LOL, I'll pass this one... Awesome vid btw
The only thing you should explain is how to DELETE object in Golang. 😅
'Who's using a 32-bit machine in 2022' You got a lot of Arch users screaming slurs right now :D
Can you make real project depends on pointers , or give us more pointers examples, specially with big.Int
15:57 it's wrong when you say "it's a function and not a method"
First
You are even faster than my own pinned comment.
Man golang intellisense is sloom op windows ik snap wel wrm jij ubuntu gebruik
Bro is coding grenade logic for pubg 💀
LMAO
Hi Anthony, If my understanding is correct, here czcams.com/video/mqH21m0MsWk/video.html:
```func (player Player) takeDamageFromExplosion() { } ``` is a method ? If not, can you please explain why?
I had same doubt but I think it's a method takeDamageFromExplosion has a receiver of type Player, indicated by (player Player) before the method name.
@@imnishantsharma that's true! you are right.
Your videos are good and very much informative. But i would request you to put some effort on typing. It is very much irritating to see all those mistakes throughout each and every videos. If you can't control those typing mistakes, keep it that way. Mechanical kb doesn’t help typing. Sorry if that hurts.
I feel ya. It is indeed very annoying. Even for me. It depends on the day though. I think it gets better in later videos.
I want to hit the like button, but it's on 666 :(
🥲
Pointers, learn C instead