给定一个类型,例如:type LicenseCards struct { cards *[]int}我不会展示创建切片的代码。但这删除了最上面的项目,忽略了零长度的情况。func (licenseCards *LicenseCards) PopLicenseCard() int { l := len(*licenseCards.cards) ret := (*licenseCards.cards)[l-1] *licenseCards.cards = (*licenseCards.cards)[:l-1] return ret}如果我从切片中删除最后一项并返回指向已删除项的指针,是否保证它仍然可用?
1 回答

慕桂英4014372
TA贡献1871条经验 获得超13个赞
如果有东西正在使用内存,GC 将不会释放它。
您的代码的另一点是,在使用 . 运营商例如:只需这样做:l := len(licenseCards.cards)。
此外,您不需要卡片和接收器都是指针。如果你不介意我想建议这个:
type LicenseCards struct {
cards []int
}
func (lc *LicenseCards) PopLicenseCard() int {
l := len(lc.cards)
ret := lc.cards[l-1]
lc.cards = lc.cards[:l-1]
return ret
}
- 1 回答
- 0 关注
- 109 浏览
添加回答
举报
0/150
提交
取消