我上周開始學習golang,我正在用golang重寫一個python項目。我知道golang基本上沒有繼承的概念,人們建議使用嵌入代替。在我的項目中,我有一個名為 的基礎結構,一個名為 MyBase 的擴展結構。 攜帶2d數組的映射,每個2d數組都可以通過枚舉指定的鍵訪問。在另一個文件夾中,我有一個擴展.文件夾結構如下所示MyBaseAdvBaseMyBaseTopTeamAdvBaseroot|--- main.go|--- base |--- base.go (MyBase struct & AdvBase struct) |--- commons.go|--- team |--- topteam |--- tt.go (TopTeam struct)在tt.go中,我初始化了MyBase中定義的映射,我希望它將反映在嵌入了MyBase或AdvBase的所有結構中。// base.gopackage baseimport "fmt"type MyBase struct { max_num int myTool map[KIND]Tool}func (b MyBase) SetTool( k KIND, mat [][]int) { b.myTool[k].SetMat(mat)}func (b MyBase) ShowTool(k KIND) { b.myTool[k].Show()}type AdvBase struct { MyBase}func NewAdvBase(max_num_ int) *AdvBase { ab := AdvBase{MyBase{max_num: max_num_}} return &ab}type Tool struct { mat [][]int}func (t Tool) SetMat(mat_ [][]int) { t.mat = mat_}func (t Tool) Show() { fmt.Println(t.mat)}// commons.gopackage basetype KIND intconst ( T1 KIND = 0 T2 KIND = 1 T3 KIND = 2 T4 KIND = 3) // tt.gopackage teamsimport "base"type TopTeam struct { base.AdvBase}func NewTeam(k_ int) *TopTeam { p := base.NewAdvBase(k_) tt := TopTeam{*p} T2 := base.T2 // I assign the 2d array holding by the map with key=T2 tt.SetTool(T2, [][]int {{1,2,3,4}, {4,5,6},{7,8,9,10,11}}) return &tt}// main.gopackage mainimport ( "base" teams "team/topteam")func main() { pp := teams.NewTeam(3) // calling this should issue tt.SetTool pp.ShowTool(base.T2) // so this line should show the assigned array}但是,在運行代碼后,key=T2 的數組始終為空。我整個下午都在調試這個問題,但仍然不知道代碼出了什么問題。在運行時,程序中最多可以創建 10 個實例,每個 TopTeam 維護一個 映射,并且每個實例都保存一個矩陣(2d 數組),其大小或內容可能會不時更改。我希望在創建映射和工具后保持它們的地址不變,但是工具持有的數組可以更改。是否可以在 go 中實現此功能?TopTeamToolTool
1 回答

夢里花落0921
TA貢獻1772條經驗 獲得超6個贊
您必須更改一些內容:
首先,您需要更改以使用指針接收器:SetMat
func (t *Tool) SetMat(mat_ [][]int) {
...
}
沒有它,接收并修改它的副本,然后被丟棄。使用指針接收器,將修改用于調用 的實例。SetMattSetMattSetMat
然后,您需要更改要存儲的地圖,而不是:*ToolTool
myTool map[KIND]*Tool
否則,將返回 的副本,而不是指向映射中存儲的實例的指針。myTool[x]ToolTool
然后,您必須更改映射的初始化位置。使用當前設置時,映射具有按值,因此,如果映射中不包含元素,則返回一個空實例。使用指針時,該空實例將為 nil,從而導致緊急。Tool
func (b MyBase) SetTool( k KIND, mat [][]int) {
t:=b.myTool[k]
if t==nil {
t=&Tool{}
b.myTool[k]=t
}
t.SetMat(mat)
}
- 1 回答
- 0 關注
- 83 瀏覽
添加回答
舉報
0/150
提交
取消