You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- 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.
518
518
- 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.
519
519
- Go is a strictly typed language and it likes to be explicit about everything.
520
520
- 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 :
600
600
> - You do not intend to modify the receiver
601
601
> - The receiver is a map, a func, a chan, a slice, a string, or an interface value (because internally it’s already a pointer)
602
602
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
+
603
630
## Interfaces
604
631
605
632
- An interface is like an abstract class in Python.
0 commit comments