I'm new to go and trying to implement an interface for video operations (download, upload, transcode). In my download method I'm creating a Reader and assigning it to struct variable 'fileContent'. I'd then like to access the Reader in my upload method but it's throwing a runtime error.
panic: runtime error: invalid memory address or nil pointer dereference
Below is a link to my code in go playground. Any help would be great.
The problem is that you're using non-pointer receiver:
func (b BaseVideo) Download() (err error) {
b.fileContent = bytes.NewReader([]byte("abc"))
return nil
}
This means your Download()
method gets a copy of the BaseVideo
value you're calling it on. You modify this copy inside the method (you assign a new Reader
to the fileContent
field), but the original BaseVideo
will not be modified.
Solution: use a pointer receiver:
func (b *BaseVideo) Download() (err error) {
b.fileContent = bytes.NewReader([]byte("abc"))
return nil
}
Of course if you modify the receiver to be a pointer, the type BaseVideo
will no longer implement the Video
interface, only a pointer to BaseVideo
, so also modify NewBaseVideo
to return a pointer to the struct value: *BaseVideo
. You can achieve this by taking the address of the struct literal:
func NewBaseVideo(path, name string) Video {
return &BaseVideo{
Path: path,
Name: name,
}
}
If you want to mutate the value in a methods, the receiver of the method should be a pointer. Replace
func (b BaseVideo) Download() (err error)
and such with
func (b *BaseVideo) Download() (err error)
Working code on the playground: https://play.golang.org/p/hZ8-RwzVYh.