Skip to content

Commit 75c1aed

Browse files
committed
runtime: slightly better error message for assertion panics with identical looking types
Fixes #18911. Change-Id: Ice10f37460a4f0a66cddeacfe26c28045f5e60fe Reviewed-on: https://go-review.googlesource.com/116255 Run-TryBot: Robert Griesemer <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Keith Randall <[email protected]>
1 parent b219a68 commit 75c1aed

File tree

4 files changed

+41
-1
lines changed

4 files changed

+41
-1
lines changed

src/runtime/error.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,13 @@ func (e *TypeAssertionError) Error() string {
3636
return "interface conversion: " + inter + " is nil, not " + e.assertedString
3737
}
3838
if e.missingMethod == "" {
39-
return "interface conversion: " + inter + " is " + e.concreteString +
39+
msg := "interface conversion: " + inter + " is " + e.concreteString +
4040
", not " + e.assertedString
41+
if e.concreteString == e.assertedString {
42+
// provide slightly clearer error message
43+
msg += " (types from different packages)"
44+
}
45+
return msg
4146
}
4247
return "interface conversion: " + e.concreteString + " is not " + e.assertedString +
4348
": missing method " + e.missingMethod

test/fixedbugs/issue18911.dir/a.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Copyright 2018 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package a
6+
7+
var X interface{} = struct{ x int }{}

test/fixedbugs/issue18911.dir/b.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright 2018 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package main
6+
7+
import "./a"
8+
import "strings"
9+
10+
func main() {
11+
defer func() {
12+
p, ok := recover().(error)
13+
if ok && strings.Contains(p.Error(), "different packages") {
14+
return
15+
}
16+
panic(p)
17+
}()
18+
19+
// expected to fail and report two identical looking (but different) types
20+
_ = a.X.(struct{ x int })
21+
}

test/fixedbugs/issue18911.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// rundir
2+
3+
// Copyright 2018 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+
package ignore

0 commit comments

Comments
 (0)