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

给定一个类型,例如:


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

}

如果我从切片中删除最后一项并返回指向已删除项的指针,是否保证它仍然可用?


慕虎7371278
浏览 110回答 1
1回答

慕桂英4014372

如果有东西正在使用内存,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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go