英文:
How do I type-assert that a value is a pointer (to a string)?
问题
我正在尝试创建一个方法,该方法将返回泛型类型的长度。如果我们有一个字符串,我们调用len(string),或者如果它是一个interface{}类型的数组,我们也调用len()。这个方法运行良好,但是如果你传递一个指向字符串的指针,它就不起作用了(我假设对于数组和切片也会有同样的问题)。那么我该如何检查是否有一个指针,并对其进行解引用呢?
func (s *Set) Len(i interface{}) int {
if str, ok := i.(string); ok {
return len(str)
}
if array, ok := i.([]interface{}); ok {
return len(array)
}
if m, ok := i.(map[interface{}]interface{}); ok {
return len(m)
}
return 0
}
英文:
I'm trying to create a method that will return the length of a generic type. If we have a string, we call len(string), or if its an array of interface{} type, we call len() on that as well. This works well, however, it doesnt work in you pass in a pointer to a string (I'm assuming I'd have the same problem with arrays and slices as well). So how can I check if I have a pointer, and dereference it?
func (s *Set) Len(i interface{}) int {
if str, ok := i.(string); ok {
return len(str)
}
if array, ok := i.([]interface{}); ok {
return len(array)
}
if m, ok := i.(map[interface{}]interface{}); ok {
return len(m)
}
return 0
}
答案1
得分: 8
你可以像处理其他类型一样处理它:
if str, ok := i.(*string); ok {
return len(*str)
}
此时,你可能想要使用类型开关(type switch),而不是更冗长的if语句:
switch x := i.(type) {
case string:
return len(x)
case *string:
return len(*x)
…
}
英文:
You can do the same thing as for the other types:
if str, ok := i.(*string); ok {
return len(*str)
}
At this point you may want to use a type switch instead of the more verbose ifs:
switch x := i.(type) {
case string:
return len(x)
case *string:
return len(*x)
…
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论