Go语言认为条件语句内的变量未使用?

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

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)

huangapple
  • 本文由 发表于 2022年3月1日 11:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/71303279.html
匿名

发表评论

匿名网友

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

确定