Skip to content

Commit 8a25cc4

Browse files
committed
cmd/compile: revise error msg in type assertion ptr/non-ptr condition
Revise the error message under the condition that type assertion has mismatching pointer/non-pointer type. This adds a better error hint for the situation that a user writes x.(*I), but they meant to write x.(I). Fixes #43673
1 parent 928bda4 commit 8a25cc4

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

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

+6-1
Original file line numberDiff line numberDiff line change
@@ -999,7 +999,12 @@ func typecheck1(n *Node, top int) (res *Node) {
999999
yyerror("impossible type assertion:\n\t%v does not implement %v (missing %v method)\n"+
10001000
"\t\thave %v%0S\n\t\twant %v%0S", n.Type, t, missing.Sym, have.Sym, have.Type, missing.Sym, missing.Type)
10011001
} else {
1002-
yyerror("impossible type assertion:\n\t%v does not implement %v (missing %v method)", n.Type, t, missing.Sym)
1002+
origMissing := missing
1003+
if implements(derefall(n.Type), t, &missing, &have, &ptr) {
1004+
yyerror("impossible type assertion:\n\t%v does not implement %v (but %v does)", n.Type, missing.Sym, derefall(n.Type))
1005+
} else {
1006+
yyerror("impossible type assertion:\n\t%v does not implement %v (missing %v method)", n.Type, t, origMissing.Sym)
1007+
}
10031008
}
10041009
n.Type = nil
10051010
return n

test/fixedbugs/issue43673.go

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// errorcheck
2+
3+
// Copyright 2021 The Go Authors. All rights reserved.
4+
// Use of this source code is governed by a BSD-style
5+
// license that can be found in the LICENSE file.
6+
7+
// Issue 43673
8+
package main
9+
10+
type I interface {
11+
M()
12+
}
13+
14+
type T struct{}
15+
16+
func (t *T) M() {}
17+
18+
func main() {
19+
var i I
20+
_ = i.(*I) // ERROR " *I does not implement M (but I does)"
21+
}

0 commit comments

Comments
 (0)