Skip to content

Instantly share code, notes, and snippets.

@abhishek-buragadda
Last active December 20, 2020 06:17
Show Gist options
  • Save abhishek-buragadda/37124fc3b86ae820bf6e960cc877d038 to your computer and use it in GitHub Desktop.
Save abhishek-buragadda/37124fc3b86ae820bf6e960cc877d038 to your computer and use it in GitHub Desktop.
nil in golang
************nil in golang*******************
- nil == nil // true .
The above statement is straight forward.
But suppose there is a pointer of a struct whose value is nil.
```
var t *T = nil
var p P = t
p == nil // returns false.
```
Why is the above statement false? because nil is typed value in GO.
What happens to the above state
(A*, nil) == (nil, nil) , so even though the values are same, the types differ and hence the result is false.
RealWorld example:
Suppose you created a custom error with your own fields and of type error like below.
```
type struct MyError {
}
func(m MyError) String() string {
}
func(m MyError) Error() string {
}
MyError *a = &MyError{}
```
If there is a function test(), that return error type in which we return nil of MyError pointer type.
```
func test() (error){
MyError *a = nil
..
return a
}
temp := test()
if temp == nil { // false.
//do something.
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment