英文:
Is a slice's underlying array accessible if the slice is shrunk?
问题
给定一个类型,如下所示:
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
}
如果我从切片中移除最后一个元素并返回指向被移除元素的指针,那么它是否保证仍然可用?
英文:
Given a type such as:
type LicenseCards struct {
    cards *[]int
}
I won't show the code that creates the slice. But this removes the top item, ignoring the zero-length case.
func (licenseCards *LicenseCards) PopLicenseCard() int {
    l := len(*licenseCards.cards)
    ret := (*licenseCards.cards)[l-1]
    *licenseCards.cards = (*licenseCards.cards)[:l-1]
    return ret
}
If I remove the last item from the slice and return a pointer to the removed item, is it guaranteed to still be available?
答案1
得分: 2
正如@Volker所说,如果有东西在使用内存,垃圾回收器将不会释放它。
你的代码中还有一个问题,就是在使用.运算符之前不需要解引用指针(使用*运算符),只需这样做:l := len(licenseCards.cards)。
此外,你不需要将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
}
英文:
As @Volker said the memory will not be released by the GC if something is using it.
Another point with your code is that you do not need to dereference a pointer (using * operator) before using the . operator eg: just do this: l := len(licenseCards.cards).
Also you don't need cards and the receiver to both be pointers. If you don't mind I would like to suggest this:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论