I have a use case to define a function ( in example it is "Process") which is common for two struct (Bellow example: StudentStats and EmployeeStats) and for each struct, it has its own implementation for "Pending" function.
When I run the example i get following error :
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4990ba]
What is the right approach to solve this issue ?
package main
import "fmt"
type Stats struct {
Pending func(int, int) int
}
func (g *Stats) Process() {
fmt.Println("Pending articles: ", g.Pending(1, 2))
}
// StatsGenerator is an interface for any entity for a case
type StatsGenerator interface {
Process()
}
// Creating structure
type StudentStats struct {
Stats
name string
language string
Tarticles int
Particles int
}
type EmployeeStats struct {
Stats
name string
Tarticles int
Particles int
}
func (a *StudentStats) Pending(x int, y int) int {
// Logic to identify if the accountis in pending state for stucent
return x + y
}
func (a *EmployeeStats) Pending(x int, y int) int {
// Logic to identify if the accountis in pending state for employe
return x - y
}
// Main method
func main() {
sResult := StudentStats{
name: "Sonia",
language: "Java",
Tarticles: 1,
Particles: 1,
}
eResult := EmployeeStats{
name: "Sonia",
Tarticles: 1,
Particles: 4,
}
var statsGenerator = []StatsGenerator{
&sResult, &eResult,
}
for _, generator := range statsGenerator {
generator.Process()
}
}
Processcalls the individual functionPending(as is in your code) you cannot easily solve this with composition.