While I was reading "the little go" book, I found that it suggests to write a function without any return value. So I proceed to test that function but the program won't compile and give me this "... used as value"error. Anyone knows what is going on here?
package main
import (
"fmt"
)
func log(message string) {
fmt.Println(message)
}
func main() {
msg := log("just a message")
fmt.Println(msg)
}
I know that this function is trivial (maybe the question is stupid also). But I am just curious to know if this type of function legal in Go?
The function here you have used
func log(message string){
fmt.Println(message)
}
Actually returns nothing.
But you are assigning it to a variable is incorrect. Since function returns nothing.
msg := log("just a message")
and that's why the error
.. used as value
You can call it directly.
func main() {
log("just a message")
}
Check out on go playground
A function that returns nothing is perfectly valid:
func log(message string) {
// .. do stuff
}
But treating it as though it returns something is invalid:
msg := log("foo") // what do you expect to be assigned to msg? log() returns nothing!
Your log() function does not return anything so you can’t assign it result to a variable (msg := ...)
import(
"fmt"
)
func log(message string){
fmt.Println(message)
}
func main(){
log("just a message")
}