表达式无效¶
ID: go/useless-expression
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- maintainability
- correctness
- external/cwe/cwe-480
- external/cwe/cwe-561
Query suites:
- go-security-and-quality.qls
如果表达式没有任何效果(例如更改变量值或生成输出),并且出现在其值被忽略的上下文中,则可能表示代码缺失或存在潜在错误。
建议¶
仔细检查表达式,确保它不是错误的症状。
示例¶
以下示例显示了一个名为 Timestamp
的命名类型,它是 int
的别名,表示自某个纪元以来经过的秒数表示的时间戳。 addDays
方法返回一个时间戳,该时间戳比另一个时间戳晚指定天数,而不修改该时间戳。
但是,当在函数 test
中使用 addDays
时,其结果会被丢弃,这可能是因为程序员错误地认为 addDays
会更新时间戳。
package main
import "fmt"
type Timestamp int
func (t Timestamp) addDays(d int) Timestamp {
return Timestamp(int(t) + d*24*3600)
}
func test(t Timestamp) {
fmt.Printf("Before: %s\n", t)
t.addDays(7)
fmt.Printf("After: %s\n", t)
}
相反,addDays
的结果应该被赋值回 t
package main
import "fmt"
func testGood(t Timestamp) {
fmt.Printf("Before: %s\n", t)
t = t.addDays(7)
fmt.Printf("After: %s\n", t)
}