gpt4 book ai didi

go - 在条件语句中声明但未使用的变量

转载 作者:IT王子 更新时间:2023-10-29 02:13:46 27 4
gpt4 key购买 nike

我在条件语句之外声明了一些变量(offsetIlimitI)。在条件语句中,我试图为它们赋值,然后在条件语句之后使用这些值进行查询。

var (
number, size, offset, limit string
offsetI, limitI uint64
)

// Get the string values for number, size, offset, and limit
// ...

if size != "" {

// Parse the number value
numberI, err := strconv.ParseUint(number, 10, 64)
if err != nil {...}

// Parse the size value
limitI, err = strconv.ParseUint(size, 10, 64)
if err != nil {...}

// Calculate the offset
offsetI = numberI * limitI

} else {

// Parse the limit value
limitI, err := strconv.ParseUint(limit, 10, 64) // limitI declared and not used
if err != nil {...}

// Parse the offset value
offsetI, err = strconv.ParseUint(offset, 10, 64)
if err != nil {...}
}

// Make the query using offsetI and limitI
result, err := s.GetAllPaginated(offsetI, limitI)
if err != nil {...}

我不打算在 else 语句的范围内重新声明 limitI 变量,但我需要使用 := 用于声明新的 err 变量的运算符。

我唯一能想到的就是单独声明另一个 err 变量,这样我就可以使用常规赋值语句:

} else {

var err error // New

// Regular assignment statement now
limitI, err = strconv.ParseUint(limit, 10, 64)
if err != nil {...}

我希望能够在不必声明额外的错误变量的情况下执行此操作。

最佳答案

额外的 var error 很尴尬,但这是解决这种情况的常用方法。 The spec on scoping说(强调我的):

The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.

所以在你的例子中,那个简短的变量声明声明了一个不同的 limitI 作用域为“最里面的包含 block ”。由于它只“存在”到下一个右大括号,因此不会被使用。

在您的特定情况下,一个选项可能是在 if/else 之外声明 err,因为它在两个内部范围内都使用,因此您可以改用 use = := 的那些函数返回 error。那么就没有声明“内部 limitI”,也没有未使用的变量问题。

像这样的“阴影”情况也会产生意外行为而不是错误。 go vet -shadow tries to detect "[v]ariables that may have been unintentionally shadowed"并且,不同但相关,gordonklaus/ineffasign概括了“未使用的变量”检查以检测无用的赋值,即使它们不是声明。

关于go - 在条件语句中声明但未使用的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175345/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com