Jameo
Jameo

Reputation: 4607

How do I type-assert that a value is a pointer (to a string)?

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
}

Upvotes: 3

Views: 3222

Answers (1)

Steve M
Steve M

Reputation: 8516

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

Upvotes: 8

Related Questions