Go 认为条件语句中的变量未被使用?
我遇到一种情况,如果某些东西无法分配变量,我会在条件语句中分配它,但是 Go 似乎认为该变量未被使用。
for index, value := range group.Values {
timestamp, err := time.Parse(time.RFC3339, value.Timestamp)
if err != nil {
strings.ReplaceAll(value.Timestamp, "+0000", "")
timestamp, err := time.Parse(time.RFC3339, value.Timestamp)
if err != nil {
log.Printf("Error parsing timestamp for point %s: (%s) %v", value.Context+"_"+value.ID, value.Timestamp, err)
continue
}
}
event := new(SplunkEvent)
event.Time = timestamp.Unix()
Go 认为条件语句中的变量 timestamp
未被使用。这是为什么?我明明是有条件后直接用的。
I have a situation where if something fails to assign a variable I instead assign it within a conditional statement however Go seems to think this variable is unused.
for index, value := range group.Values {
timestamp, err := time.Parse(time.RFC3339, value.Timestamp)
if err != nil {
strings.ReplaceAll(value.Timestamp, "+0000", "")
timestamp, err := time.Parse(time.RFC3339, value.Timestamp)
if err != nil {
log.Printf("Error parsing timestamp for point %s: (%s) %v", value.Context+"_"+value.ID, value.Timestamp, err)
continue
}
}
event := new(SplunkEvent)
event.Time = timestamp.Unix()
Go believes the variable timestamp
inside the conditional statement is unused. Why is that? I have clearly used it directly after the condition.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嵌套(内部)
timestamp
声明遮盖了外部时间戳 - 因此外部时间戳永远不会被设置。因此,由于从未使用过内部值,因此编译错误是有效的。要修复此问题,请将声明的赋值运算符替换为
=
以(重新)使用外部作用域的timestamp
(以及err) 值:
The nested (inner)
timestamp
declaration shadows the outer one - so the outer one is never set. So since the inner value is never used, the compilation error is valid.To fix, replace
:=
declared assignment operator with=
to (re)use the outer scope'stimestamp
(anderr
) values: