Null Pointer Challenge 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
bytescan

bytescan

14 Followers

ByteScan is a Cyber Security Consulting Firm that offers security auditing services for a number of blockchains, with a special focus on third-generation dapps.