Golang: expected identifier on left side of :=syntax

Viewed 4541

I'm new to Golang and while trying to implement a simple client server model, I'm getting this error expected identifier on left side of :=syntax on line:

kvs.listener, err := net.Listen("tcp", ":9999")

Specifically the error is under kvs.

I'm not sure why this is happening. If I replace kvs.listener with a simple ln (i.e. no struct) the error go away. Can someone please help me in fixing this?

Thanks!

2 Answers

:= is a short variable declaration. As its name says, it is to declare variables.

kvs.listener is not an identifier of a new variable you wish to declare, it's likely a field of an existing variable (or a variable of some package).

When you don't want a new variable, use simple assignment:

kvs.listener, err = net.Listen("tcp", ":9999")

If the err variable does not yet exist, you have to declare it prior:

var err error
kvs.listener, err = net.Listen("tcp", ":9999")

Try to do like

 newVar, err := net.Listen("tcp", ":9999")
 kvs.listener = newVar

where newVar is a variable that you not used in the program

Related