英文:
In go, is this line creating a new empty map with string as key and value?
问题
这行代码是在Go语言中创建一个新的空映射(map),其中键和值都是字符串类型。
英文:
keys := []string{}
In go, is this line creating a new empty map with string as key and value?
答案1
得分: 5
不,那是创建一个空字符串切片。
这是一个键和值都为字符串类型的空映射:
keys := map[string]string{}
英文:
No, that's creating an empty string slice.
This is an empty map with string as key and value:
keys := map[string]string{}
答案2
得分: 2
如果你不知道类型是什么,你可以使用reflect包进行检查:
package main
import (
"fmt"
"reflect"
)
func main() {
keys := []string{}
fmt.Println(reflect.TypeOf(keys))
fmt.Println(reflect.TypeOf(keys).Elem())
}
输出结果:
[]string
string
这表示一个空的字符串切片。
另一个例子是检查切片中的类型:
keys := []string{}
anotherKeys := []map[string]string{}
fmt.Println("keys: ", reflect.TypeOf(keys).Elem())
fmt.Println("anotherKeys: ", reflect.TypeOf(anotherKeys).Elem())
输出结果:
keys: string
anotherKeys: map[string]string
注意:
Elem()
英文:
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()
答案3
得分: 0
不,[]string
是一个字符串切片。
如果你想要一个键和值都是字符串类型的空映射,那么 map[string]string
就是正确的类型。在 Playground 中尝试以下示例代码,你就可以看到结果:
package main
import (
"fmt"
"reflect"
)
func printKind(i interface{}) {
fmt.Printf("Kind of %#v: %s\n", i, reflect.TypeOf(i).Kind())
}
func main() {
emptySlice := []string{}
printKind(emptySlice)
emptyMap := map[string]string{}
printKind(emptyMap)
}
英文:
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\n", i, reflect.TypeOf(i).Kind())
}
func main() {
emptySlice := []string{}
printKind(emptySlice)
emptyMap := map[string]string{}
printKind(emptyMap)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论