mirror of
https://github.com/golang/go
synced 2024-11-25 13:47:57 -07:00
gofmt: simplify "x, _ = range y" to "x = range y"
(inspired by CL 3529041 by hitchmanr@gmail.com) R=rsc CC=golang-dev https://golang.org/cl/3527042
This commit is contained in:
parent
2bdb2e78fe
commit
e2da3b6498
@ -10,11 +10,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
type compositeLitFinder struct{}
|
type simplifier struct{}
|
||||||
|
|
||||||
func (f *compositeLitFinder) Visit(node interface{}) ast.Visitor {
|
func (s *simplifier) Visit(node interface{}) ast.Visitor {
|
||||||
if outer, ok := node.(*ast.CompositeLit); ok {
|
switch n := node.(type) {
|
||||||
|
case *ast.CompositeLit:
|
||||||
// array, slice, and map composite literals may be simplified
|
// array, slice, and map composite literals may be simplified
|
||||||
|
outer := n
|
||||||
var eltType ast.Expr
|
var eltType ast.Expr
|
||||||
switch typ := outer.Type.(type) {
|
switch typ := outer.Type.(type) {
|
||||||
case *ast.ArrayType:
|
case *ast.ArrayType:
|
||||||
@ -41,17 +43,25 @@ func (f *compositeLitFinder) Visit(node interface{}) ast.Visitor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// node was simplified - stop walk
|
// node was simplified - stop walk (there are no subnodes to simplify)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case *ast.RangeStmt:
|
||||||
|
// range of the form: for x, _ = range v {...}
|
||||||
|
// can be simplified to: for x = range v {...}
|
||||||
|
if n.Value != nil {
|
||||||
|
if ident, ok := n.Value.(*ast.Ident); ok && ident.Name == "_" {
|
||||||
|
n.Value = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// not a composite literal or not simplified - continue walk
|
return s
|
||||||
return f
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func simplify(node interface{}) {
|
func simplify(node interface{}) {
|
||||||
var f compositeLitFinder
|
var s simplifier
|
||||||
ast.Walk(&f, node)
|
ast.Walk(&s, node)
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user