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 quicktemplate 模版快速入门

Golang 有很多的模版引擎,自带的 `html/template` 也很好,大多数情况都能满足需求,只是有些逻辑、条件判断不好在模版里实现, `quicktemplate` 是个很好的选择。...

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms