Function that returns a boolean

Hello,

I have a function that returns a boolean like this:

func isHere(email string){
var status bool
status = false

// do database verification
if something {
status = true
}

return status

}


now in main
Can I do this

func main(){
if isHere(“danny”){
// say danny is here
}else{
// say danny is not here
}
}

This needs to be

func isHere(email string) bool {

for it to actually return a bool. Apart from that, and that the body of the function can be a bit simplified depending on what you’re actually doing, yes. Assuming that isHere is also in package main, that is.

What did you try, and what happened when you did?

I’m trying to check if a user email exists on my database, so I can return a boolean and use the function like this (if isHere(“email”){// do stuffs}) in main…(guess that’s good practice)

The first time I tried it nothing happened, everything just halted with no response, so I assumed I could either not use it that way or I had some errors in my database code.

in this case you don’t need a status variable to return true or false. simply do

return true

or

return false

when is needed.

1 Like

Oh!!! Never knew, that’s cool. I’m coming from Java, I learnt to always do that.

HOwever, is it bad to do? Will the code still work? Peharps that’s why everything froze.

is nothing wrong to return a variable but this is a simple code and just no need. anyway, written like this, your code should work:

package main

var something bool

func isHere(email string) bool{
	var status bool
	status = false

	if something {
		status = true
	}
	return status
}


func main(){
	something=true // TOGGLE HERE TRUE AND FALSE
	if isHere("danny"){
		println("say danny is here")
	}else{
		println("say danny is not here")
	}
}
1 Like

Please can I do this ?

func Login(nick, pass string){

if is := IsSignedUp(nick);is == true && uPass := getPass(nick); uPass == pass{
    //set session and log user in
}else{
    // send failure message
}

}

On the if block

is not a good practice to merge many code lines in one. remember that golang is a simple language and your code must be readable.

try this

is := IsSignedUp(nick)
uPass := getPass(nick)
if is == true && uPass == pass{
}

tip: do not try to find other languages in golang. try to understand golang :wink:

2 Likes

That was useful, thanks a lot!!! :grinning:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.