亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有多個結構的通用功能

具有多個結構的通用功能

Go
暮色呼如 2022-08-01 16:49:47
我有一個用例來定義一個函數(例如它是“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 mainimport "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 casetype StatsGenerator interface {    Process()}// Creating structuretype 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 methodfunc 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()    }}
查看完整描述

2 回答

?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

好吧,這是我會給出的答案。


我會創建函數來創建新的 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中面向對象編程的評論。


查看完整回答
反對 回復 2022-08-01
?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

問題在于您的統計信息類型嵌入了結構:Stats


type 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()Stats


sResult := StudentStats{

    Stats: Stats{

        Pending: func(a, b int) int {

            // Do something.

        }

    },

    // [..]

}


查看完整回答
反對 回復 2022-08-01
  • 2 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號