Home  >  Article  >  Backend Development  >  Type conversion of golang function return value

Type conversion of golang function return value

WBOY
WBOYOriginal
2024-04-23 14:42:01765browse

There are two methods for function return value type conversion: Type Assertion checks whether the value is compatible with a specific type, and an error is reported if it is not compatible; Type Conversion does not check compatibility and converts directly. In practice, you can convert floating point types to integers, or convert integers in tuples to strings.

Type conversion of golang function return value

Type conversion of function return value in Go language

In Go language, the type of function return value can be usedtype assertion or type conversion to convert.

Type Assertion

Use type assertion to check whether a value is compatible with a specific type and convert the value to the expected type. If the type is incompatible, an error will occur. :

func GetValue() interface{} {
    return "Hello, world!"
}

func main() {
    value := GetValue()
    // 检查 value 是否为字符串类型
    if str, ok := value.(string); ok {
        fmt.Println(str) // 输出: Hello, world!
    }
}

Type Conversion

Use type conversion to convert the type of the value to the expected type, regardless of whether the value is compatible or not, the conversion will be performed:

func main() {
    var num float64 = 3.14
    // 将 float64 转换为 int
    numInt := int(num)
    fmt.Println(numInt) // 输出: 3
}

Practical Case

The following is a practical case to demonstrate how to convert the type of function return value:

func GetEmployeeInfo() (string, int) {
    return "John Doe", 30
}

func main() {
    name, age := GetEmployeeInfo()

    // 将 age 转换为 string 类型
    ageStr := strconv.Itoa(age)
    fmt.Println("Employee Name:", name)
    fmt.Println("Employee Age:", ageStr)
}

Output:

Employee Name: John Doe
Employee Age: 30

The above is the detailed content of Type conversion of golang function return value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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