如何在 Go 中查詢物件的型別

Suraj Joshi 2023年1月30日 2020年6月9日
  1. 在 Go 中字串格式以查詢資料型別
  2. 型別斷言方法
如何在 Go 中查詢物件的型別

資料型別指定與有效 Go 變數關聯的型別。Go 中有四類資料型別,如下所示:

  • 基本型別:數字,字串和布林值

  • 集合型別:陣列和結構

  • 參考型別:指標,切片,Map,函式和通道

  • 介面型別

我們可以使用字串格式,反射包和型別斷言在 Go 中找到物件的資料型別。

在 Go 中字串格式以查詢資料型別

我們可以將軟體包 fmtPrintf 功能與特殊格式設定一起使用。使用 fmt 顯示變數的可用格式選項是:

格式 描述
%v 以預設格式列印變數值
%+v 用值新增欄位名稱
%#v 該值的 Go 語法表示形式
%T 值型別的 Go 語法表示形式
%% 文字百分號;不消耗任何價值

我們在 fmt 包中使用%T 標誌來在 Go 語言中找到物件的型別。

package main

import "fmt"

func main() {
    i := 18
    fmt.Printf("Datatype of i : %T\n", i)

    s := "Dixya Lyaho"
    fmt.Printf("Datatype of s : %T\n", s)

    f := 25.32
    fmt.Printf("Datatype of f : %T\n", f)
}       

輸出:

Datatype of i : int
Datatype of s : string
Datatype of f : float64

Go reflect

我們也可以使用 reflect 包來查詢物件的資料型別。reflect 包的 Typeof 函式返回值可以通過 .String() 轉換為字串資料型別。

package main

import (
    "fmt"
    "reflect"
)

func main() {
    o1 := "string"
    o2 := 10
    o3 := 1.2
    o4 := true
    o5 := []string{"foo", "bar", "baz"}
    o6 := map[string]int{"apple": 23, "tomato": 13}

    fmt.Println(reflect.TypeOf(o1).String())
    fmt.Println(reflect.TypeOf(o2).String())
    fmt.Println(reflect.TypeOf(o3).String())
    fmt.Println(reflect.TypeOf(o4).String())
    fmt.Println(reflect.TypeOf(o5).String())
    fmt.Println(reflect.TypeOf(o6).String())

}      

輸出:

string
int
float64
bool
[]string
map[string]int

型別斷言方法

型別斷言方法返回一個布林變數,以判斷斷言操作是否成功。我們使用 switch 方法來串聯執行幾個型別斷言,以找到物件的資料型別。

package main

import (
    "fmt"
)

func main() {
    var x interface{} = 3.85
    switch x.(type) {
    case int:
        fmt.Println("x is of type int")
    case float64:
        fmt.Println("x is of type float64")
    default:
        fmt.Println("x is niether int nor float")

    }

}      

輸出:

x is of type float64
Author: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn