Cannot call non-function <variable> error in Golang

In Golang, the "cannot call non-function <variable>" error occurs when you try to call a variable that is not a function. This error indicates that you are trying to use a variable as a function, but the variable does not have a function type.

Let's consider an example to understand this error. Consider the following Golang program:

Example

package main

import "fmt"

func main() {
    message := "Hello, World!"
    printMessage(message)
}

func printMessage(str string) {
    fmt.Println(str)
}

In this program, we declare a variable message and initialize it with the value "Hello, World!". We then call a function printMessage and pass message as an argument to the function.

However, when we try to compile and run this program, we will encounter the following error:

Output

./main.go:7:17: cannot call non-function message (type string)

This error occurs because we are trying to call the message variable as if it were a function. The message variable is not a function, it is a string variable.

To fix this error, we need to pass the message variable as an argument to the printMessage function, like this:


Example

package main

import "fmt"

func main() {
    message := "Hello, World!"
    printMessage(message)
}

func printMessage(str string) {
    fmt.Println(str)
}

In this modified program, we pass the message variable as an argument to the printMessage function. This code will compile and run without any errors.

In summary, the "cannot call non-function <variable>" error in Golang occurs when you try to call a variable that is not a function. To fix this error, you need to ensure that you only call functions and not variables.


Most Helpful This Week