Skip to content

Commit

Permalink
fix: define a correct zero value for an not initialized interface{}
Browse files Browse the repository at this point in the history
  • Loading branch information
mvertes authored Feb 4, 2020
1 parent 4fd6a2d commit 23dfef0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
12 changes: 12 additions & 0 deletions _test/interface19.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package main

import "fmt"

var I interface{}

func main() {
fmt.Printf("%T %v\n", I, I)
}

// Output:
// <nil> <nil>
10 changes: 8 additions & 2 deletions interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -1443,8 +1443,14 @@ func (interp *Interpreter) cfg(root *node, pkgID string) ([]*node, error) {
}
}
for _, c := range n.child[:l] {
index := sc.add(n.typ)
sc.sym[c.ident] = &symbol{index: index, kind: varSym, typ: n.typ}
var index int
if sc.global {
// Global object allocation is already performed in GTA.
index = sc.sym[c.ident].index
} else {
index = sc.add(n.typ)
sc.sym[c.ident] = &symbol{index: index, kind: varSym, typ: n.typ}
}
c.typ = n.typ
c.findex = index
}
Expand Down
14 changes: 13 additions & 1 deletion interp/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,23 @@ func genValueInterface(n *node) func(*frame) reflect.Value {
}
}

func zeroInterfaceValue() reflect.Value {
n := &node{kind: basicLit, typ: &itype{cat: nilT, untyped: true}}
v := reflect.New(reflect.TypeOf((*interface{})(nil)).Elem()).Elem()
return reflect.ValueOf(valueInterface{n, v})
}

func genValueInterfaceValue(n *node) func(*frame) reflect.Value {
value := genValue(n)

return func(f *frame) reflect.Value {
return value(f).Interface().(valueInterface).value
v := value(f)
if v.Interface().(valueInterface).node == nil {
// Uninitialized interface value, set it to a correct zero value.
v.Set(zeroInterfaceValue())
v = value(f)
}
return v.Interface().(valueInterface).value
}
}

Expand Down

0 comments on commit 23dfef0

Please sign in to comment.