Skip to content

Commit 87e2c2f

Browse files
committed
pointer receiver vs. value receiver
1 parent 2c91680 commit 87e2c2f

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

content/posts/go-notes.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,7 @@ https://www.ardanlabs.com/blog/2017/05/language-mechanics-on-stacks-and-pointers
514514
## Maps and Structs under the hood
515515

516516
- While maps may resemble to dictionary type in Python but they're not the same.
517-
- Within the Go runtime, a map is implemented as a pointer to a struct. Passing a map to a function means that you are copying a pointer and which is why you should consider carefully before using maps for function input parameters or return values.
517+
- Within the Go runtime, a map is implemented as a pointer to a struct. Passing a map to a function means that you are copying a pointer and which is why you should consider carefully before using maps for function input parameters or return values. Changing the `map[key]:value` passed as function parameter will result in changing the original map data which can have unintended consequences.
518518
- Passing around Maps in function calls is discouraged because they say nothing about the values contained within; nothing explicitly defines any keys in the map, so the only way to know what they are is to trace through the code.
519519
- Go is a strictly typed language and it likes to be explicit about everything.
520520
- If you need to pass around a data structure with key:value pairs, instead of passing a map consider using struct or a slice of structs.
@@ -600,6 +600,33 @@ Use a value receiver when :
600600
> - You do not intend to modify the receiver
601601
> - The receiver is a map, a func, a chan, a slice, a string, or an interface value (because internally it’s already a pointer)
602602
603+
A method with a value receiver can’t check for nil and panics if invoked with a nil receiver
604+
605+
```
606+
type Person struct{
607+
Name string
608+
Age int
609+
}
610+
611+
func (p Person) AllowedToDrive() bool{
612+
if p.Age < 18 {
613+
return false
614+
}
615+
616+
return true
617+
}
618+
619+
func main(){
620+
// pointer variable points to data of type Person. p is declared but not initialized. Current value is nil
621+
var p *Person
622+
623+
// panics because inside the receiver function we're de-referencing value (nil) which doesn't exist
624+
fmt.Println(p.AllowedToDrive())
625+
}
626+
```
627+
628+
But what happens if we declared `p` as `var p Person` instead? In that case default value of `p` will be the zero value of the fields inside the `Person` struct.
629+
603630
## Interfaces
604631

605632
- An interface is like an abstract class in Python.

0 commit comments

Comments
 (0)