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

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

Is a slice's underlying array accessible if the slice is shrunk?

问题

给定一个类型,如下所示:

  1. type LicenseCards struct {
  2. cards *[]int
  3. }

我不会展示创建切片的代码。但是这段代码会移除顶部的元素,忽略长度为零的情况。

  1. func (licenseCards *LicenseCards) PopLicenseCard() int {
  2. l := len(*licenseCards.cards)
  3. ret := (*licenseCards.cards)[l-1]
  4. *licenseCards.cards = (*licenseCards.cards)[:l-1]
  5. return ret
  6. }

如果我从切片中移除最后一个元素并返回指向被移除元素的指针,那么它是否保证仍然可用?

英文:

Given a type such as:

  1. type LicenseCards struct {
  2. cards *[]int
  3. }

I won't show the code that creates the slice. But this removes the top item, ignoring the zero-length case.

  1. func (licenseCards *LicenseCards) PopLicenseCard() int {
  2. l := len(*licenseCards.cards)
  3. ret := (*licenseCards.cards)[l-1]
  4. *licenseCards.cards = (*licenseCards.cards)[:l-1]
  5. return ret
  6. }

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和接收器都设置为指针。如果你不介意的话,我想建议这样做:

  1. type LicenseCards struct {
  2. cards []int
  3. }
  4. func (lc *LicenseCards) PopLicenseCard() int {
  5. l := len(lc.cards)
  6. ret := lc.cards[l-1]
  7. lc.cards = lc.cards[:l-1]
  8. return ret
  9. }
英文:

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:

  1. type LicenseCards struct {
  2. cards []int
  3. }
  4. func (lc *LicenseCards) PopLicenseCard() int {
  5. l := len(lc.cards)
  6. ret := lc.cards[l-1]
  7. lc.cards = lc.cards[:l-1]
  8. return ret
  9. }

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:

确定