Skip to content

Commit 34b563f

Browse files
odeke-emmdempsky
authored andcommitted
cmd/compile: improve error for wrong type in switch
Fixes #10561. Provides a better diagnostic message for failed type switch satisfaction in the case that a value receiver is being used in place of the pointer receiver that implements and satisfies the interface. Change-Id: If8c13ba13f2a8d81bf44bac7c3a66c12921ba921 Reviewed-on: https://go-review.googlesource.com/35235 Reviewed-by: Matthew Dempsky <[email protected]> Run-TryBot: Matthew Dempsky <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent ba1a65f commit 34b563f

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/cmd/compile/internal/gc/swt.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,13 @@ func typecheckswitch(n *Node) {
162162
yyerror("impossible type switch case: %L cannot have dynamic type %v"+
163163
" (wrong type for %v method)\n\thave %v%S\n\twant %v%S", n.Left.Right, n1.Type, missing.Sym, have.Sym, have.Type, missing.Sym, missing.Type)
164164
} else if !missing.Broke {
165-
yyerror("impossible type switch case: %L cannot have dynamic type %v"+
166-
" (missing %v method)", n.Left.Right, n1.Type, missing.Sym)
165+
if ptr != 0 {
166+
yyerror("impossible type switch case: %L cannot have dynamic type %v"+
167+
" (%v method has pointer receiver)", n.Left.Right, n1.Type, missing.Sym)
168+
} else {
169+
yyerror("impossible type switch case: %L cannot have dynamic type %v"+
170+
" (missing %v method)", n.Left.Right, n1.Type, missing.Sym)
171+
}
167172
}
168173
}
169174
}

test/switch6.go

+14
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,17 @@ func f1(e interface{}) {
3030
default: // ERROR "multiple defaults in switch"
3131
}
3232
}
33+
34+
type I interface {
35+
Foo()
36+
}
37+
38+
type X int
39+
40+
func (*X) Foo() {}
41+
func f2() {
42+
var i I
43+
switch i.(type) {
44+
case X: // ERROR "impossible type switch case: i \(type I\) cannot have dynamic type X \(Foo method has pointer receiver\)"
45+
}
46+
}

0 commit comments

Comments
 (0)