How to properly initialize an empty slice in Go: var s []int vs s := make([]int, 0)?
Hi everyone! I recently started learning Go and encountered a problem with initializing empty slices. There seem to be two popular ways:
1. `var s []int` — declaration without initialization (nil slice)
2. `s := make([]int, 0)` — initialization with an empty slice using make
I've read that both options can be used, and in some cases they behave the same. For example, if I do `fmt.Println(s)`, both output `[]`. But I noticed strange behavior during JSON serialization. Here's an example:
```go
package main
import (
"encoding/json"
"fmt"
)
type MyStruct struct {
Items []string
}
func main() {
s1 := MyStruct{}
s2 := MyStruct{Items: []string{}}
json1, _ := json.Marshal(s1)
json2, _ := json.Marshal(s2)
fmt.Println(str
No answers yet.
Log in to leave an answer
Blogs