如何键入断言值是指针(到字符串)?

Jam*_*meo 2 go

我正在尝试创建一个返回泛型类型长度的方法.如果我们有一个字符串,我们调用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
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*e M 7

您可以执行与其他类型相同的操作:

if str, ok := i.(*string); ok {
    return len(*str)
}
Run Code Online (Sandbox Code Playgroud)

此时,您可能希望使用类型开关而不是更详细的ifs:

switch x := i.(type) {
case string:
    return len(x)
case *string:
    return len(*x)
…
}
Run Code Online (Sandbox Code Playgroud)