Home > Backend Development > Golang > Why Does My Go Function Call Result in the 'Used as Value' Error?

Why Does My Go Function Call Result in the 'Used as Value' Error?

DDD
Release: 2024-12-19 10:02:10
Original
1003 people have browsed it

Why Does My Go Function Call Result in the

"used as value" in Function Call

In Go, functions can be invoked to evaluate their values, which can be used in conditional statements. However, when evaluating function values, it's crucial to ensure proper function declaration and invocation.

In the provided code snippet:

if sumThis(1,2) > sumThis(3,4){
    fmt.Println("test")
} else {
    fmt.Println("derp")
}
Copy after login

The function sumThis is invoked multiple times to calculate its value. However, the error message indicates that sumThis is "used as value," which means the function call is attempting to assign the result of the function call to a variable without specifying a return type.

To resolve this, you need to declare a return type for the sumThis function. In Go, functions must explicitly declare their return types. The function should be declared as follows:

func sumThis(a, b int) int {
    return a + b
}
Copy after login

By specifying the return type as int, the function will return the result of the calculation. Now, the code will compile and run successfully, printing either "test" or "derp" depending on the results of the function calls.

The above is the detailed content of Why Does My Go Function Call Result in the 'Used as Value' Error?. For more information, please follow other related articles on the PHP Chinese website!

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