From 133ecf9210d4e3560916c6e5ece2b91a97399a9d Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Sun, 1 Mar 2015 20:59:15 -0800 Subject: [PATCH] go/types: better error message for use of _ in type switch Change-Id: If690d2d9607b3632451df2681c293835321ed9bd Reviewed-on: https://go-review.googlesource.com/6413 Reviewed-by: Alan Donovan --- go/types/stmt.go | 9 ++++++++- go/types/testdata/stmt0.src | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/go/types/stmt.go b/go/types/stmt.go index fa60f64d..3917336d 100644 --- a/go/types/stmt.go +++ b/go/types/stmt.go @@ -456,7 +456,14 @@ func (check *Checker) stmt(ctxt stmtContext, s ast.Stmt) { check.invalidAST(s.Pos(), "incorrect form of type switch guard") return } - check.recordDef(lhs, nil) // lhs variable is implicitly declared in each cause clause + + if lhs.Name == "_" { + // _ := x.(type) is an invalid short variable declaration + check.softErrorf(lhs.Pos(), "no new variable on left side of :=") + lhs = nil // avoid declared but not used error below + } else { + check.recordDef(lhs, nil) // lhs variable is implicitly declared in each cause clause + } rhs = guard.Rhs[0] diff --git a/go/types/testdata/stmt0.src b/go/types/testdata/stmt0.src index 4c840367..073e83b2 100644 --- a/go/types/testdata/stmt0.src +++ b/go/types/testdata/stmt0.src @@ -540,6 +540,7 @@ func typeswitches() { } switch x /* ERROR "declared but not used" */ := x.(type) {} + switch _ /* ERROR "no new variable on left side of :=" */ := x.(type) {} switch x := x.(type) { case int: