我有一个用例来定义一个函数(例如,它是“Process”),这对于两个结构是常见的(以下示例:StudentStats和EmployeeStats)
对于每个结构,它都有自己的“待定”功能实现。
当我运行示例时,出现以下错误:
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()
}
}
最佳答案
好的,在这里我会给出答案。
我将创建函数来创建一个新的StudentStat/EmployeeStat,以正确设置Pending
函数:
func NewStudentStats(name, language string, tarticles, particles int) *StudentStats {
stats := &StudentStats{
name: name,
language: language,
Tarticles: tarticles,
Particles: particles,
}
// setting the correct Pending function to the Stats struct inside:
stats.Stats.Pending = stats.Pending
return stats
}
有关完整代码,请参见工作Playground示例。还请注意我对Go语言中有关面向对象编程的评论。
关于go - 具有多个结构的通用功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65722416/