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

王林
Release: 2024-02-05 11:49:27
forward
1148 people have browsed it

确定 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
}
Copy after login

The signature of the Visit method is as follows

Visit(tree antlr.ParseTree) interface{}
Copy after login

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)
Copy after login

The output is as follows:

TYPE -> exec.DataType                   
VALUE -> 5
Copy after login

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")
}
Copy after login

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
        }
}
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template