Go变量在if语句中不会被覆盖。

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

Go variable doesn't get overwritten in if statement

问题

以下是翻译好的内容:

duration := 1 * time.Hour
if true {
	duration, err := time.ParseDuration("5s")
	_ = duration // 如果我没有这个,它会给我一个未使用的持续时间声明错误
	if err != nil {
		log.Fatal(err)
	}
}

fmt.Println(duration) // 输出 1 小时

我猜问题在于在 if 语句中重新声明了 duration 作为局部变量有没有一种语法上好的方法来解决这个问题
英文:
duration := 1 * time.Hour
if true {
	duration, err := time.ParseDuration("5s")
	_ = duration // if I don't have this, it gives me a duration declared not used error
	if err != nil {
		log.Fatal(err)
	}
}

fmt.Println(duration) // prints 1 hour

I guess the issue here is that duration is declared again as local var within if statement. Is there a syntactically good way to resolve this?

答案1

得分: 9

确实,在if块中你再次声明了duration变量。我处理这个问题的方式是在if块之前声明err变量(通常在函数的开头,因为error变量几乎总是需要的...)。

var err error
duration := 1 * time.Hour
if true {
    duration, err = time.ParseDuration("5s")
    if err != nil {
        log.Fatal(err)
    }
}

请注意,我只翻译了代码部分,其他内容不包括在内。

英文:

Indeed, you declare the duration variable again in the if block. My way to do this is to declare err before the if block (usually at the beginning of the function, as an error variable is pretty much always needed...).

var err error
duration := 1 * time.Hour
if true {
    duration, err = time.ParseDuration("5s")
    if err != nil {
        log.Fatal(err)
    }
}

答案2

得分: 4

问题是当time.ParseDuration返回错误时,你是否希望覆盖duration。如果不希望覆盖,那么我会这样写:

duration := 1 * time.Hour
if true {
    d, err := time.ParseDuration("5s")
    if err != nil {
        log.Fatal(err)
    } else {
        duration = d
    }
}

如果在错误的情况下你不关心旧值,那么@julienc的答案也是一样好的。

英文:

The question is whether you want duration to be overwritten when time.ParseDuration returns an error or not. If not, then I would write

duration := 1 * time.Hour
if true {
    d, err := time.ParseDuration("5s")
    if err != nil {
        log.Fatal(err)
    } else {
        duration = d
    }
}

If you don't care about the old value in the case of an error, @julienc's answer is just as good.

答案3

得分: 1

Go是一种块结构的编程语言。通常,变量的声明具有最小的作用域。

变量duration在外部(func)作用域中声明并使用,并且也在内部(if)作用域中设置。变量err在内部(if)作用域中声明并使用。例如,

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	duration := 1 * time.Hour
	if true {
		var err error
		duration, err = time.ParseDuration("5s")
		if err != nil {
			log.Fatal(err)
		}
	}
	fmt.Println(duration)
}

输出:

5s

使用短变量声明是行不通的。短变量声明只能重新声明在同一块中先前声明的变量。

func main() {
	duration := 1 * time.Hour
	if true {
		duration, err := time.ParseDuration("5s")
		if err != nil {
			log.Fatal(err)
		}
	}
	fmt.Println(duration)
}

错误:

duration declared and not used

变量duration在外部(func)作用域中声明并使用。它也在内部(if)作用域中声明(而不是重新声明)并设置,但未使用。

参考资料:

Block (programming)

Block scope (computer science)

The Go Programming Language Specification

The Go Programming Language Specification: Blocks

The Go Programming Language Specification: Declarations and scope

The Go Programming Language Specification: Short variable declarations

英文:

Go is a block-structured programming language. Generally, variables are declared with minimal scope.

The variable duration is declared and used in the outer (func) scope and is also set in the inner (if) scope. The err variable is declared and used in the inner (if) scope. For example,

package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	duration := 1 * time.Hour
	if true {
		var err error
		duration, err = time.ParseDuration("5s")
		if err != nil {
			log.Fatal(err)
		}
	}
	fmt.Println(duration)
}

Output:

5s

Using a short variable declaration won't work. A short variable declaration can only redeclare variables that are originally declared earlier in the same block.

func main() {
	duration := 1 * time.Hour
	if true {
		duration, err := time.ParseDuration("5s")
		if err != nil {
			log.Fatal(err)
		}
	}
	fmt.Println(duration)
}

Error:

duration declared and not used

The variable duration is declared and used in the outer (func) scope. It is also declared (not redeclared) and set, but not used, in the inner (if) scope.

References:

Block (programming)

Block scope (computer science)

The Go Programming Language Specification

The Go Programming Language Specification: Blocks

The Go Programming Language Specification: Declarations and scope

The Go Programming Language Specification: Short variable declarations

huangapple
  • 本文由 发表于 2014年7月3日 23:41:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/24558056.html
匿名

发表评论

匿名网友

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

确定