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

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

How to detect if an interface{} is a 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())
}
英文:

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

答案1

得分: 6

如果你已经知道类型,可以使用类型开关(type switch):

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

如果你不知道类型,可以使用 if reflect.TypeOf(v).Kind() == reflect.Ptr {}

playground

英文:

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 {}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年10月9日 11:32:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/33029462.html
匿名

发表评论

匿名网友

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

确定