The user with no hat
The user with no hat

Reputation: 10846

How to detect if an interface{} is a pointer?

I'm wondering how can you know if the interface is of type pointer.

package main

import "fmt"
import "reflect"

type str struct {
    a, b string
}

func main() {
    var s str
    x := &s
    t := reflect.TypeOf(interface{}(x))
    fmt.Printf("%v", t.Size())
}

Upvotes: 0

Views: 65

Answers (1)

OneOfOne
OneOfOne

Reputation: 99234

Use a type switch if you already know the type(s):

switch v.(type) {
case *str:
    return "*str"
case str:
    return "str"
}

If you don't, then you can use if reflect.TypeOf(v).Kind() == reflect.Ptr {}

playground

Upvotes: 6

Related Questions