我有一个用例来定义一个函数(例如它是“Process”),这对于两个结构(Bellow示例:StudentStats和 EmployeeStats)是常见的,对于每个结构,它都有自己的“Pending”函数实现。
当我运行该示例时,我得到以下错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4990ba]
解决此问题的正确方法是什么?
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()
}
}
呼啦一阵风
慕码人2483693
相关分类