File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ Title: Golang: Understanding 'null' and nil
2
+ Tags: golang, golang-nil
3
+
4
+ Golang does not allow NULL, or its version nil, where some languages do.
5
+
6
+ package main
7
+ import "fmt"
8
+
9
+ func main() {
10
+ someRandom := getString()
11
+ fmt.Println(someRandom)
12
+ }
13
+
14
+ func getString() string {
15
+ return nil // This WON'T compile
16
+ }
17
+
18
+ Because the return of getString is a ** value** (and a struct is a value too, incidentally), it cannot be nil.
19
+
20
+ This allows us to avoid many NULL pointer errors in other languages.
21
+
22
+ A 'NULL' pointer error is still possible, however. But only with actual ** pointers or references** (a slice is a common example).
23
+
24
+ package main
25
+ import "fmt"
26
+
27
+ type SomeStruct struct {
28
+ name string
29
+ }
30
+
31
+ func main() {
32
+ s := getSomeStruct()
33
+ fmt.Println(s.name) // It will crash here
34
+ }
35
+
36
+ func getSomeStruct() *SomeStruct {
37
+ return nil // This WILL compile
38
+ }
39
+
40
+ In this case, since getSomeStruct() returns a pointer, we can return nil.
41
+
42
+ And as such if we try to reference the 'name' attribute of the struct we will crash.
You can’t perform that action at this time.
0 commit comments