Similar to continue, to exit an event [SOLVED]

Hey there, I’m trying to exit an event using a continue, the same I use inside a loop, but that’s not compiling, compiler says me “continue is not in a loop”. How can I go out of that event inside my condition?

package main

import (
	"strings"

	"hlsat.com.br/funcoes_gerais"
	"hlsat.com.br/servidor_tcp"
)

func main() {
	var crcCalculado, crcPacote /*, TipoMsg, InfoSerialNum*/ string

	server := servidor_tcp.New("0.0.0.0:2007")

	/*
		server.OnNewClient(func(c *servidor_tcp.Client) {

		})
	*/

	server.OnNewMessage(func(c *servidor_tcp.Client, message string) {

		Rec := strings.TrimSpace(strings.ToUpper(message))

		crcCalculado = retornaCRC(funcoes_gerais.CopyStr(Rec, 5, len(Rec)-12))
		crcPacote = funcoes_gerais.CopyStr(funcoes_gerais.RightStr(Rec, 8), 1, 4)

		if crcCalculado != crcPacote {
			print("Pacote quebrado...")
			continue
		}
		print("TESTE")
		//print(RightStr(Rec, 8))

		c.Send(Rec)

	})

	/*
		server.OnClientConnectionClosed(func(c *servidor_tcp.Client, err error) {

		})
	*/

	server.Listen()
}

Tnx.

Do you want to exit the function early? In that case, you should use return.

return is most often used to return a value from a function, but it can also be used to return early.

By the way, declaring variables in main but only using them in the function passed to OnNewMessage sounds like a recipe for mysterious bugs, since if multiple messages arrive simultaneously, they will share the same variables for crcCalculado and crcPacote.

3 Likes

Hey @leogazio,

Like @andybalholm has suggested, simply replace continue with return. You are not currently in a loop, but are inside of a function closure, so you would exit it the same way you would with a regular early return from a function.

1 Like

Thank you guys, I really forgot the return lol, that’s because I’m not used to work with GO, it’s still new to me and I like it :slight_smile:

We all forget stuff here and there! Keep up the good work though and it will all become easier over time :smiley:

1 Like

:slight_smile:

1 Like

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