如何检测接口{}是否为指针?

The*_*hat 0 pointers go

我想知道你怎么知道接口是否是类型指针.

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())
}
Run Code Online (Sandbox Code Playgroud)

One*_*One 6

如果您已经知道类型,请使用类型开关:

switch v.(type) {
case *str:
    return "*str"
case str:
    return "str"
}
Run Code Online (Sandbox Code Playgroud)

如果你没有,那么你可以使用 if reflect.TypeOf(v).Kind() == reflect.Ptr {}

playground