是否有可能在Golang中返回Integer或Float的函数?

问题描述:

I'd like to create a function which returns an integer value if a condition passes inside the function and a floating point number otherwise. How can I handle this with Go? Thank you!

我想创建一个函数,如果条件在函数内部传递并且返回浮点,则该函数返回整数值 否则编号。 如何使用Go处理? 谢谢! p> div>

Yes, it is possible. You just have to return it as a float:

func doStuff(flag bool) float32 {
    if flag {
        return 1.1
    }
    return 1
}

func main() {
    num1 := doStuff(true)
    num2 := doStuff(false)
    fmt.Println("Num1: ", num1)
    fmt.Println("Num2: ", num2)
}

The only thing that matters is how you format it for displaying.

Demo

That is not directly possible in Golang. In general, statically typed languages will usually do their best to prevent this scenario, because it makes type checking very difficult. The type checking is necessary because integer and floating point are inherently incompatible.

You could return interface{}. However, how will the caller know what you returned?

Is this something that you are looking for?

package main

import "fmt"

func number(intOrFloat bool) interface{} {
    if intOrFloat { //return int if this flag is true
        return 5
    }
    return 5.5
}

func main() {
    printType(number(true))
    printType(number(false))
    printType("Nihanth")
}

func printType(value interface{}) {
    if number, ok := value.(int); ok {
        fmt.Printf("I have got an integer %d
", number)
    } else if number, ok := value.(float64); ok {
        fmt.Printf("I have got float %f
", number)
    } else {
        fmt.Printf("%+v is not integer or float", value)
    }
}