Home >Backend Development >Golang >Determine the type of interface {} value returned by a function in Golang

Determine the type of interface {} value returned by a function in Golang

王林
王林forward
2024-02-05 11:49:271147browse

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

Question content

I have a function that returns a value from an enumeration. The enumeration is defined as follows:

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
}

The signature of the Visit method is as follows

Visit(tree antlr.ParseTree) interface{}

After calling the method, I receive a value of type DataType and print the type and return value in the following lines.

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

The output is as follows:

TYPE -> exec.DataType                   
VALUE -> 5

So far so good, but I need to do a comparison and that's the problem I have, that I don't know much about Golang. I have the following:

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

This is where I don't know how to proceed with validating the return type, if I try the following lines I never execute the code I want, which in this case is to return VOID. My question is how to compare the return types to perform a specific action based on the result. I've also tried the following:

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

            return execResult
        }
}

In this case, the situation inside the switch is not satisfied either. My question is basically how to determine the type of interface{} value returned from a function call.


Correct answer


I think @Charlie Tumahai is right: the problem is a values ​​mismatch. I tried a little example on Go Playground and it works as expected: if DataType is returned from Visit, then with ## The comparison of #DataType can be true.

The returned type

must be of DataType type. The Visit2 method demonstrates this: it returns an int64, which is never equal to BREAK. This is described in the

Go Programming Language Specification under

Comparison Operators:

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
}

The above is the detailed content of Determine the type of interface {} value returned by a function in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete