GolangNote

Golang笔记

GoLang 获取变量类型

Permalink

Go 语言可通过 reflect 包获取某个变量的类型:

golang reflect

Go: reflect
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
    "fmt"
    "reflect"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Println(reflect.TypeOf(b), reflect.ValueOf(b).Kind())
    fmt.Println(reflect.TypeOf(s), reflect.ValueOf(s).Kind())
    fmt.Println(reflect.TypeOf(n), reflect.ValueOf(n).Kind())
    fmt.Println(reflect.TypeOf(f), reflect.ValueOf(f).Kind())
    fmt.Println(reflect.TypeOf(a), reflect.ValueOf(a).Kind(), reflect.ValueOf(a).Index(0).Kind())
}

输出:

Bash: out put
1
2
3
4
5
bool bool
string string
int int
float64 float64
[]string slice string

也可以通过 type+switch 组合来识别变量类型

Go: type+switch
1
2
3
4
5
6
7
8
switch v2 := v.(type) {
case string:
    fmt.Println("is string", v2)
case int:
    fmt.Println("is int", v2)
default:
    fmt.Println("other")
}

本文网址: https://golangnote.com/topic/49.html 转摘请注明来源

Related articles

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Write a Comment to "GoLang 获取变量类型"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms