I'm trying to understand why I'm getting the error: invalid memory address or nil pointer dereference
Let's say I have this code (this is not the real one but similar):
type (
Cat struct {
Name string
}
Dog struct {
Name string
}
Pets struct{
c *Cat
d *Dog
}
)
func (c *Cat) Rename(d Dog) string {
err := SomeErrorChecks()
name := strings.TrimSpace(d.Name)
c.Name = name // In this line is where I get the error
return err
}
func (p *Pets) SomeFunction() string{
p.d = &Dog{}
p.c = &Cat{}
p.d.Name = " Foo "
err := p.c.Rename(*p.d)
return err
}
func main(){
//some code
err := SomeFunction()
//some error handling not relevant
}
I've checked that strings.TrimSpace(d.Name)
returns de desired string. And I've checked that the type of c.Name
is string. So, why I can't assing name
to c.Name
if both are the same type?