Last active
May 15, 2024 13:42
-
-
Save getvictor/bff0fa45185630e264a40476207d8e4d to your computer and use it in GitHub Desktop.
Nil slice vs empty slice. Full article at https://victoronsoftware.com/posts/nil-slice-versus-empty-slice-in-go/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/* | |
According to Go guidelines at https://go.dev/wiki/CodeReviewComments#declaring-empty-slices | |
When declaring an empty slice, prefer | |
var t []string | |
over | |
t := []string{} | |
*/ | |
import "fmt" | |
const usePreference = true | |
const nullPointer = false | |
func getEmptySlice() []string { | |
if usePreference { | |
var slice []string | |
return slice | |
} else { | |
slice := []string{} | |
return slice | |
} | |
} | |
func main() { | |
// Sanity check. | |
slice := getEmptySlice() | |
if slice == nil { | |
fmt.Println("Slice is nil.") | |
} else { | |
fmt.Println("Slice is NOT nil.") | |
} | |
fmt.Printf("Slice is: %#v\n", slice) | |
// Test append. | |
slice = append(slice, "bozo") | |
fmt.Printf("Test append: %#v\n", slice) | |
// Test for loop | |
slice = getEmptySlice() | |
for range slice { | |
fmt.Println("We are in a for loop.") | |
} | |
// Test len | |
fmt.Printf("len: %#v\n", len(slice)) | |
// Test pass by pointer. | |
passByPointer(&slice) | |
fmt.Printf("len after passByPointer: %#v\n", len(slice)) | |
// Test null pointer. | |
if nullPointer { | |
var nullSlice *[]string | |
fmt.Printf("Crash: %#v\n", len(*nullSlice)) | |
} | |
} | |
func passByPointer(slice *[]string) { | |
fmt.Printf("passByPointer len: %#v\n", len(*slice)) | |
*slice = append(*slice, "bozo") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment