as signature instead of the type it self ?
func function () *T
Instead
Func function () T
What is the benefit ?
T in this case is an copy of an type. Different goroutines can act on it without affecting the others. With pointers they access the same memory and when the wrize to that shared space it can lead to problems. Copies are rather expensive for bigger objects, so sometimes the originals are pooled and only accessed through pointers.
what about method receivers ? can i always use pointer receiver instead of value receiver ? when should i use value receiver ?
Think of receivers as a first argument to your function. Non-pointer receivers will copy. Now depending on what you want to do — mutate or not, and how big the data structure is, you may prefer one over the other. Although the rule of thumb is, be consistent with your receivers, and when in doubt, use a pointer receiver.
https://go.dev/tour/methods/8 don 't forget however, that copying small stuff (usually < 64 bytes) is very cheap and pointers usually cause allocation on the heap, which creates garbage that the garbage collector will have to clean up. If you create too much garbage you will unnecessarily slow down your code.
It depends. maps and slices are passed by reference. In case the T is a slice or a map, you are essentially passing a pointer to a reference.
sometimes this is necessary if you want to append onto a slice for example
You mean a pointer to a slice? Never seen that.
append has a new allocation inside (when resizing) if you dont pass pointer you will get wrong behavior
pointer usage is reasonable to me
It's not "wrong behaviour". Its the behaviour you wrote. The computer does what it is being told.
Its reasonable, and fine to do. But what I'm saying is I have seen more returning the new slice than passing by pointer.
so u should use pointer not get your wrong behavior
Although I'm curious if one is "more optimized" by the compiler than the other.
The pointer one is likely superior if anything
I doubt. Let me dump the SSA.
Обсуждают сегодня