keys := []string{}
In go, is this line creating a new empty map with string as key and value?
No, that's creating an empty string slice.
This is an empty map with string as key and value:
keys := map[string]string{}
If you don't know what is the type, you can always check using reflect package:
package main
import (
"fmt"
"reflect"
)
func main() {
keys := []string{}
fmt.Println(reflect.TypeOf(keys))
fmt.Println(reflect.TypeOf(keys).Elem())
}
Output:
[]string
string
Which means an empty slice of string.
Another eg to check the types inside the slice:
keys := []string{}
anotherKeys := []map[string]string{}
fmt.Println("keys: ", reflect.TypeOf(keys).Elem())
fmt.Println("anotherKeys: ", reflect.TypeOf(anotherKeys).Elem())
Output:
keys: string
anotherKeys: map[string]string
NB: Elem()
No, []string
is a slice of strings.
If you want an empty map with strings as the type for both keys and values, then map[string]string
would be the correct type. Try the following example code in the Playground to see it for yourself:
package main
import (
"fmt"
"reflect"
)
func printKind(i interface{}) {
fmt.Printf("Kind of %#v: %s
", i, reflect.TypeOf(i).Kind())
}
func main() {
emptySlice := []string{}
printKind(emptySlice)
emptyMap := map[string]string{}
printKind(emptyMap)
}