Go問題

1,詳解slice
https://www.jianshu.com/p/030aba2bff41

2,詳解Map
https://mp.weixin.qq.com/s/Jq65sSHTX-ucSG8TlI5Zxg

//錯誤代碼
this.tombPlayerData = make(map[AvatarID]TTombPlayerData)
this.ParentZone.GetSpaceHolder().ForeachPlayer(func(player INodePlayer) bool {
	this.tombPlayerData[player.GetAvatarID()].RoleName = player.GetName()
	this.tombPlayerData[player.GetAvatarID()].Profession = int32(player.GetProfession())
	return true
})

//糾正
this.tombPlayerData = make(map[AvatarID]*TTombPlayerData)
this.ParentZone.GetSpaceHolder().ForeachPlayer(func(player INodePlayer) bool {
	this.tombPlayerData[player.GetAvatarID()] = &TTombPlayerData{}
	this.tombPlayerData[player.GetAvatarID()].Profession = int32(player.GetProfession())
	return  true
})

3,結構體作爲map的元素時,不能直接賦值給結構體的某個字段

	//錯誤代碼,編譯器報錯:reports assignments direcliy to a struct field of a map
	var npcPos = make(map[int32]Vector3)
	npcPos[0].X = 0
	npcPos[0].Y = 0
	npcPos[0].Z = 0

	//糾正
	npcPos[0] = Vector3{X: float32(pos[0]), Y: float32(pos[1]), Z: float32(pos[2])}

詳解:https://blog.csdn.net/zhngcho/article/details/82424962

4,強轉
A(interface類型)強轉成B(struct),從而使用B中的一些接口,但前提是A中的所有接口在B中必須得有實現

type IA interface {
	GetName(id int) string
	GetID(name string) int
}

type TB struct {
	mapData map[int]*TC
	...
}

func (this *TB) GetName(id int) string {
	...
}
func (this *TB) GetID(name string) int {
	...
}

...

func (this *TB) GetDataInfo(id int) *TC {
	return this.mapData[id]
}

使用:
GetIA().(TB).GetDataInfo(id)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章