首页 > 后端开发 > Golang > Go 中如何在没有实例的情况下获取类型?

Go 中如何在没有实例的情况下获取类型?

Linda Hamilton
发布: 2024-10-31 06:19:02
原创
906 人浏览过

How to Get a Type Without an Instance in Go?

没有实例的 TypeOf:将结果传递给函数

在 Go 中,无需实例也可以获取“Type”那种类型的。这可以通过使用 Reflect.TypeOf() 来实现,但通常示例涉及实例。

在没有实例的情况下获取类型

在没有实例的情况下获取“类型”在一个实例中,技巧是从指向类型的指针开始,可以为该类型分配“类型化”nil。随后,.Elem() 可用于获取指向类型的reflect.Type 描述符,称为基类型。

1

2

3

4

5

6

7

8

<code class="go">t := reflect.TypeOf((*int)(nil)).Elem()

fmt.Println(t)

 

t = reflect.TypeOf((*http.Request)(nil)).Elem()

fmt.Println(t)

 

t = reflect.TypeOf((*os.File)(nil)).Elem()

fmt.Println(t)</code>

登录后复制

示例输出:

1

2

3

int

http.Request

os.File

登录后复制

传递类型

如果您需要传递类型并在开关中使用它们,请创建它们并将其存储在全局变量中以供参考:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<code class="go">var (

    intType         = reflect.TypeOf((*int)(nil))

    httpRequestType = reflect.TypeOf((*http.Request)(nil))

    osFileType      = reflect.TypeOf((*os.File)(nil))

    int64Type       = reflect.TypeOf((*uint64)(nil))

)

 

func printType(t reflect.Type) {

    switch t {

    case intType:

        fmt.Println("Type: int")

    case httpRequestType:

        fmt.Println("Type: http.request")

    case osFileType:

        fmt.Println("Type: os.file")

    case int64Type:

        fmt.Println("Type: uint64")

    default:

        fmt.Println("Type: Other")

    }

}

 

func main() {

    printType(intType)

    printType(httpRequestType)

    printType(osFileType)

    printType(int64Type)

}</code>

登录后复制

简化方法

如果您仅将类型用于比较目的,请考虑使用常量而不是reflect.Type:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<code class="go">type TypeDesc int

 

const (

    typeInt TypeDesc = iota

    typeHttpRequest

    typeOsFile

    typeInt64

)

 

func printType(t TypeDesc) {

    switch t {

    case typeInt:

        fmt.Println("Type: int")

    case typeHttpRequest:

        fmt.Println("Type: http.request")

    case typeOsFile:

        fmt.Println("Type: os.file")

    case typeInt64:

        fmt.Println("Type: uint64")

    default:

        fmt.Println("Type: Other")

    }

}

 

func main() {

    printType(typeInt)

    printType(typeHttpRequest)

    printType(typeOsFile)

    printType(typeInt64)

}</code>

登录后复制

以上是Go 中如何在没有实例的情况下获取类型?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板