Slice Created by Split at Golang

When a string without no strings is split by strings.Split(), the created slice is the same to the slice created by make(). The length of the slice doesn’t become zero.

Sample script :

package main

import (
    "fmt"
    "strings"
)

func main() {
    sample1a := strings.Split("", " ")
    fmt.Printf("%v, %v, '%v', %v, %+q\n", sample1a, len(sample1a), sample1a[0], len(sample1a[0]), sample1a[0])

    sample1b := make([]string, 1)
    fmt.Printf("%v, %v, '%v', %v, %+q\n", sample1b, len(sample1b), sample1b[0], len(sample1b[0]), sample1b[0])

    var sample2a []string
    fmt.Printf("%v, %v\n", sample2a, len(sample2a))

    sample2b := []string{}
    fmt.Printf("%v, %v\n", sample2b, len(sample2b))
}

Result :

strings.Split() : [], 1, '', 0, ""
make()          : [], 1, '', 0, ""
var                : [], 0
[]string{}      : [], 0

 Share!