How do you clear a slice in Go?

前端 未结 3 1092
死守一世寂寞
死守一世寂寞 2020-12-22 17:26

What is the appropriate way to clear a slice in Go?

Here\'s what I\'ve found in the go forums:

// test.go
package main

import (
    \"fmt\"
)

func          


        
3条回答
  •  青春惊慌失措
    2020-12-22 17:39

    I was looking into this issue a bit for my own purposes; I had a slice of structs (including some pointers) and I wanted to make sure I got it right; ended up on this thread, and wanted to share my results.

    To practice, I did a little go playground: https://play.golang.org/p/9i4gPx3lnY

    which evals to this:

    package main
    
    import "fmt"
    
    type Blah struct {
        babyKitten int
        kittenSays *string
    }
    
    func main() {
        meow := "meow"
        Blahs := []Blah{}
        fmt.Printf("Blahs: %v\n", Blahs)
        Blahs = append(Blahs, Blah{1, &meow})
        fmt.Printf("Blahs: %v\n", Blahs)
        Blahs = append(Blahs, Blah{2, &meow})
        fmt.Printf("Blahs: %v\n", Blahs)
        //fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
        Blahs = nil
        meow2 := "nyan"
        fmt.Printf("Blahs: %v\n", Blahs)
        Blahs = append(Blahs, Blah{1, &meow2})
        fmt.Printf("Blahs: %v\n", Blahs)
        fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
    }
    

    Running that code as-is will show the same memory address for both "meow" and "meow2" variables as being the same:

    Blahs: []
    Blahs: [{1 0x1030e0c0}]
    Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
    Blahs: []
    Blahs: [{1 0x1030e0f0}]
    kittenSays: nyan
    

    which I think confirms that the struct is garbage collected. Oddly enough, uncommenting the commented print line, will yield different memory addresses for the meows:

    Blahs: []
    Blahs: [{1 0x1030e0c0}]
    Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
    kittenSays: meow
    Blahs: []
    Blahs: [{1 0x1030e0f8}]
    kittenSays: nyan
    

    I think this may be due to the print being deferred in some way (?), but interesting illustration of some memory mgmt behavior, and one more vote for:

    []MyStruct = nil
    

提交回复
热议问题