-2

I need delete or resize isPrime array after CalRange func called (isPrime=nil not working)

isPrime := [size]bool{}
CalRange(size, maxİndex, isPrime[:])
isPrime = nil

Thanks all for answers I solve it like that. How to delete struct object in go?

person1 := &Person{name: "Name", age: 69}
// work with person1
// Clear person1:
person1 = nil
E doe
  • 15
  • 5

2 Answers2

1

Go is a garbage collected language, you can't delete objects from memory, you can only "clear" them. For details, see How to delete struct object in go? You also can't resize an array, an array is of fixed size (and the size is part of the type).

To clear an array, you may assign its zero value to it (which is not nil). Use a composite literal for a zero-value array, like [size]bool{}:

const size = 4
isPrime := [size]bool{true, true}
fmt.Println(isPrime)

isPrime = [size]bool{}
fmt.Println(isPrime)

Output (try it on the Go Playground):

[true true false false]
[false false false false]
icza
  • 389,944
  • 63
  • 907
  • 827
1

In Go, arrays are different from slices. Slices can be nil, but arrays can't, since they are static.

In your code above, on the line 1, the contents of isPrime are actually [false false false ...] with as many false values as your size variable allows.

Thus, your array can't really be deleted or resized. It can only be zero-valued.

If you really need to resize it, I recommend using slices instead, or creating a new array with the new size and copying the previous array's contents into it.

Ullaakut
  • 3,554
  • 2
  • 19
  • 34