Skip to content

Commit 1a09f66

Browse files
committed
adding basics on ptr vs value receiver
1 parent d41e7b6 commit 1a09f66

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,4 @@ go run . -module closingchannels
101101
* [79 - Signals](signals/main.go)
102102
* [80 - Exit](exit/main.go)
103103
* [81 - ErrGroup](errgroups/main.go)
104+
* [82 - Pointer Vs Value Receiver](ptr_vs_value_receiver/main.go)

ptr_vs_value_receivers/main.go

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package ptr_vs_value_receivers
2+
3+
/*
4+
When to use pointer vs value receiver types is a complicated topic. In order to fully
5+
understand it, we need to understand method set(s) and various caveats with mutable
6+
data (especially slice resizing and allocations etc)
7+
8+
Correctness should always win over speed.
9+
10+
Some guidelines we can follow are:
11+
12+
* If the receiver is a slice and the method doesn't reslice or reallocate, use a value
13+
* If the method needs to mutate the receiver, it must be a pointer
14+
* If the receiver is a struct containing unsafe to be copied fields, use a pointer
15+
* If the receiver is a large struct or array, a pointer MAY be more efficient (benchmark)
16+
* If methods can run concurrently with others that modify the receiver use a value if the
17+
changes should not be internally visible to the method, else use a pointer
18+
* If the receiver is a struct or array, any of whose elements is a pointer to some mutable,
19+
prefer a pointer receiver to make the intention of mutability clear to the reader
20+
* When in doubt, use a pointer
21+
22+
23+
*/
24+
25+
func Run() {
26+
27+
}

0 commit comments

Comments
 (0)