goglide-golang

What is wrong with this following code which throw pointer error


Could anyone tell me what's wrong with this code?

package main

import "fmt"

type Document struct{
    testString string
}

type Printer interface{
    Print(d *Document)
}

type Scanner interface{
    Scan(d *Document)
}

type MultiFunctionMachine struct{
     printer Printer
     scanner Scanner    
}

func (m *MultiFunctionMachine)Print(d *Document){       
    m.printer.Print(d)
}

func main(){
    doc:= Document{"test"}      
    multiMachine:= MultiFunctionMachine{}
    multiMachine.Print(&doc)
}

I couldn't figure out why it keeps throwing this following error. It seems like something is wrong with the pointers.

*panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1092b46]

     goroutine 1 [running]:
main.(*MultiFunctionMachine).Print(...)
    /Users/dmml/Documents/golang/udemyGoCourses/designPatternInGo/solidDesignPrinciples/interfaceSegrationPrinciple/main.go:85
main.main()
    /Users/dmml/Documents/golang/udemyGoCourses/designPatternInGo/solidDesignPrinciples/interfaceSegrationPrinciple/main.go:94 +0x46
exit status 2*

Solution

  • your MultiFunctionMachine struct needs to be initialized with concrete implementations for both the Printer and Scanner interfaces it holds. In other words, you need to define one or two types (structs or otherwise) that implement the Scan(d *Document) and Print(d *Document) interfaces (ie have functions with the same signature as these interfaces). Then assign these concrete types to the interface fields in MultiFunctionMachine. Only then m:MultiFunctionMachine can be used. You are getting a nil pointer dereference error because these fields were not initialized in this manner.