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?
Code:
type keyValueServer struct {
totalClients int
listener net.Listener
}
func New() KeyValueServer {
server := &keyValueServer{
totalClients: 0,
}
return server
}
func (kvs *keyValueServer) Start(port int) error {
kvs.listener, err := net.Listen("tcp", ":9999")
if err != nil {
fmt.Printf("Couldn't listen on port 9999: %s\n", err)
return nil
}
go setupConnection(kvs)
}
Thanks!
CodePudding user response:
:=
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")