fix: handle conversion of nil to an interface type

This commit is contained in:
Marc Vertes
2020-02-09 05:04:04 +01:00
committed by GitHub
parent 6c339ce562
commit 812e55b95e
3 changed files with 14 additions and 2 deletions

9
_test/type15.go Normal file
View File

@@ -0,0 +1,9 @@
package main
func main() {
err := error(nil)
println(err == nil)
}
// Output:
// true

View File

@@ -743,7 +743,7 @@ func (interp *Interpreter) cfg(root *node, pkgID string) ([]*node, error) {
if isInt(n.child[0].typ.TypeOf()) && n.child[1].kind == basicLit && isFloat(n.child[1].typ.TypeOf()) {
err = n.cfgErrorf("truncated to integer")
}
if isInterface(n.child[0].typ) {
if isInterface(n.child[0].typ) && !n.child[1].isNil() {
// Convert to interface: just check that all required methods are defined by concrete type.
c0, c1 := n.child[0], n.child[1]
if !c1.typ.implements(c0.typ) {
@@ -1695,6 +1695,9 @@ func (n *node) isNatural() bool {
return false
}
// isNil returns true if node is a literal nil value, false otherwise
func (n *node) isNil() bool { return n.kind == basicLit && !n.rval.IsValid() }
// fieldType returns the nth parameter field node (type) of a fieldList node
func (n *node) fieldType(m int) *node {
k := 0

View File

@@ -216,7 +216,7 @@ func convert(n *node) {
typ := n.child[0].typ.TypeOf()
next := getExec(n.tnext)
if c.kind == basicLit && !c.rval.IsValid() { // convert nil to type
if c.isNil() { // convert nil to type
n.exec = func(f *frame) bltn {
dest(f).Set(reflect.New(typ).Elem())
return next