首頁  >  文章  >  後端開發  >  確定 Golang 中函數傳回的介面 {} 值的類型

確定 Golang 中函數傳回的介面 {} 值的類型

王林
王林轉載
2024-02-05 11:49:271085瀏覽

确定 Golang 中函数返回的接口 {} 值的类型

問題內容

我有一個從枚舉回傳值的函數。枚舉定義如下:

type DataType int64

const (
    INT DataType = iota
    FLOAT
    STRING
    BOOL
    CHAR
    VOID
    ERROR
    BREAK
    CONTINUE
)

    func (l *TSwiftVisitor) VisitWhileInstr(ctx *parser.WhileInstrContext) interface{} {        
    if condExpression.ValType == BOOL {             
        condResult := condExpression.asBool()       
        for condResult {            
            for _, currentInstr := range ctx.InstrList().AllInstr() {
                execResult := l.Visit(currentInstr)
                fmt.Printf("TYPE -> %T\n", execResult) // Prints exec.DataType (the type)
                fmt.Printf("VALUE -> %v\n", execResult) // Prints 5 (the enum value)
                if execResult == BREAK { // This never executes
                    fmt.Println("Es break")
                    return VOID
                } else { // This executes
                    fmt.Println("Es otra mierda")
                }
            }           
            condResult = l.Visit(ctx.Expr()).(*Expression).asBool()
        }       
    } else {
        return ERROR
    }
    return VOID
}

Visit方法的簽章如下

Visit(tree antlr.ParseTree) interface{}

呼叫該方法後,我收到一個 DataType 類型的值,並在以下幾行中列印該類型和傳回值。

fmt.Printf("TYPE -> %T\n", execResult) // Prints exec.DataType (the type)
fmt.Printf("VALUE -> %v\n", execResult) // Prints 5 (the enum value)

輸出如下:

TYPE -> exec.DataType                   
VALUE -> 5

到目前為止,一切都很好,但我需要進行比較,這就是我遇到的問題,那就是我對 Golang 不太了解。我有以下內容:

if execResult == BREAK { // This never executes
    fmt.Println("It's a break")
    return VOID
} else { // This executes
    fmt.Println("It's another thing")
}

這就是我不知道如何繼續驗證返回類型的地方,如果我嘗試以下幾行,我永遠不會執行我想要的程式碼,在本例中是返回 VOID。我的問題是如何比較返回類型以根據結果執行特定操作。我還嘗試過以下方法:

switch execResult.(type) {
    case DataType:
        if execResult.(DataType) == BREAK {

            return execResult
        }
}

在這種情況下,開關內的情況也不滿足。我的問題基本上是如何確定從函數呼叫返回的介面{}值的類型。


正確答案


我認為@Charlie Tumahai 是對的:問題是價值觀不符。我嘗試了Go Playground 上的一個小範例,它的工作原理與我們預期的一樣:如果DataType 是從Visit 返回,然後與DataType 的比較可以是true。

傳回的類型必須DataType 類型。 Visit2 方法示範了這一點:它傳回一個 int64,它永遠不會等於 BREAK

Go 程式語言規範中的比較運算子下對此進行了介紹:

package main

import "fmt"

type DataType int64

const (
    INT DataType = iota
    BREAK
    CONTINUE
)

func Visit() interface{} { return BREAK }
func Visit2() interface{} {return int64(BREAK) }

func main() {
    for _, x := range []interface{}{Visit(), Visit2()} {
        fmt.Printf("x = %v, T(x) = %T : ", x, x)
        if x == BREAK {
            fmt.Println("x is BREAK")
        } else {
            fmt.Println("Cannot identify x")
        }
    }

    // Output:
    // x = 1, T(x) = main.DataType : x is BREAK
    // x = 1, T(x) = int64 : Cannot identify x
}

以上是確定 Golang 中函數傳回的介面 {} 值的類型的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除