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

huangapple go评论86阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2022年10月2日 16:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/73924433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定