go - 具有多个结构的通用功能

标签 go struct

我有一个用例来定义一个函数(例如,它是“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/

相关文章:

google-app-engine - 戈朗 : AppEngine throws operation not permitted error on Get call

go - 为什么我会从此 API 调用中收到意外的 EOF?

go - 在没有根文件夹的文件夹中压缩内容

c - 将文件写入结构体数组

c - 如何向结构传递/访问双指针?

c - 打印指向结构体的指针的二维数组

linux - 起订量 : running "moq": exec: "moq": executable file not found in $PATH

go - 从 amqp 解码消息正文时出错

c - 结构C中 ":"是什么意思

C 结构体数组和搜索 : Attempting to a match a member and prnt the entire struct if a match is found.