Nil Pointer Deference in Golang

package main

import "fmt"

type X interface {
X() string
}
func greeting(thing X) string {
return "Hello " + thing.X()
}

func main() {

fmt.Println("nil pointer dereference")
greeting(nil)
}
type myNumber struct {
n int
}
func addOne(number *myNumber) {
number.n++
}
func main() {
var number *myNumber
addOne(number)
}

Solution for nil pointer deference

Finally, to prevent this issue from further development, we suggest adding the nil checks in the coding practices.

func sample(x Named) (string, error) {
if x == nil {
return "", errors.New("x cannot be nil")
}
return "... " + x.Name(), nil
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mo Ashouri

Mo Ashouri

22 Followers

Mo has a Ph.D. in Cyber Security and is the founder of ByteScan.net, a blockchain audit firm. Mo specializes in Solidity, Rust, and Golang.