CodeQL 文档

自我赋值

ID: go/redundant-assignment
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - correctness
   - external/cwe/cwe-480
   - external/cwe/cwe-561
Query suites:
   - go-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

将变量赋值给自己通常表示存在错误,例如缺少限定符或变量名称拼写错误。

建议

仔细检查赋值,查看是否存在拼写错误或缺少限定符。

示例

在下面的示例中,结构类型 Rect 具有两个 setter 方法 setWidthsetHeight,它们分别用于更新 widthheight 字段

package main

type Rect struct {
	x, y, width, height int
}

func (r *Rect) setWidth(width int) {
	r.width = width
}

func (r *Rect) setHeight(height int) {
	height = height
}

但是,请注意,在 setHeight 中,程序员忘记使用接收器变量 r 来限定赋值左侧,因此该方法执行了将 width 参数赋值给自身的无用操作,并保持 width 字段不变。

要解决此问题,请插入限定符

package main

func (r *Rect) setHeightGood(height int) {
	r.height = height
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私