为了账号安全,请及时绑定邮箱和手机立即绑定

如果切片缩小,切片的底层数组是否可访问?

如果切片缩小,切片的底层数组是否可访问?

Go
慕虎7371278 2023-02-21 16:32:27
给定一个类型,例如: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

}


查看完整回答
反对 回复 2023-02-21
  • 1 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号