Golang:在 := 语法的左侧预期标识符。

huangapple go评论81阅读模式
英文:

Golang: expected identifier on left side of :=syntax

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Golang还不熟悉,在尝试实现一个简单的客户端服务器模型时,我遇到了这个错误:在以下代码的语法中,出现了“:=”左侧预期标识符的错误:

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

具体的错误出现在kvs下面。

我不确定为什么会出现这个错误。如果我将kvs.listener替换为一个简单的ln(即没有结构体),错误就消失了。有人可以帮我解决这个问题吗?

谢谢!

英文:

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!

答案1

得分: 14

:= 是一个短变量声明。顾名思义,它用于声明变量。

kvs.listener 不是你想要声明的新变量的标识符,它很可能是现有变量的字段(或某个包的变量)。

当你不想要一个新变量时,可以使用简单的赋值语句

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

如果 err 变量还不存在,你需要先声明它:

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

:= 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")

答案2

得分: 0

尝试像这样进行操作:

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

其中newVar是一个在程序中未使用的变量。

英文:

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

huangapple
  • 本文由 发表于 2021年9月17日 15:59:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/69219785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定