英文:
Go believes variables inside conditional statements are unused?
问题
我有一个情况,如果某个变量未能分配成功,我会在条件语句中进行分配,但是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.
答案1
得分: 1
嵌套的(内部的)timestamp
声明遮蔽了外部的声明,因此外部的声明从未被设置。因此,由于内部值从未被使用,编译错误是有效的。
要修复这个问题,将:=
声明的赋值操作符替换为=
,以便重新使用外部作用域的timestamp
(和err
)值:
timestamp, err = time.Parse(time.RFC3339, value.Timestamp)
英文:
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's timestamp
(and err
) values:
timestamp, err = time.Parse(time.RFC3339, value.Timestamp)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论