猿问

具有多个结构的通用功能

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


    }


}


暮色呼如
浏览 122回答 2
2回答

呼啦一阵风

好吧,这是我会给出的答案。我会创建函数来创建新的 StudentStat/EmployeeStat 来正确设置函数:Pendingfunc 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中面向对象编程的评论。

慕码人2483693

问题在于您的统计信息类型嵌入了结构:Statstype StudentStats struct {    Stats    // [..]}这一切都很好,但是您的类型具有字段,这是您正在调用的函数:StatsPendingProcess()type Stats struct {    Pending func(int, int) int}func (g *Stats) Process() {    fmt.Println("Pending articles: ", g.Pending(1, 2))}但是没有任何东西会给 赋予值,所以它是,并且会恐慌。Pendingnilg.Pending(1, 2)我不完全确定你的代码的意图是什么,但是要么实现为上的方法,要么在创建结构时分配一个值:Pending()StatssResult := StudentStats{    Stats: Stats{        Pending: func(a, b int) int {            // Do something.        }    },    // [..]}
随时随地看视频慕课网APP

相关分类

Go
我要回答