Home > Back-end >  Is a slice's underlying array accessible if the slice is shrunk?
Is a slice's underlying array accessible if the slice is shrunk?

Time:10-02

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?

CodePudding user response:

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
}
  •  Tags:  
  • go
  • Related