如何进行类型断言以确保一个值是指向字符串的指针?

huangapple go评论79阅读模式
英文:

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)
…
}

huangapple
  • 本文由 发表于 2014年5月7日 23:24:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/23521933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定