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

Type conversion of golang function return value

WBOY
Release: 2024-04-23 14:42:01
Original
852 people have browsed it

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

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

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

Output:

Employee Name: John Doe
Employee Age: 30
Copy after login

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!

Related labels:
source:php.cn
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