Skip to content

Commit

Permalink
fix: improve type switch clause with assign
Browse files Browse the repository at this point in the history
  • Loading branch information
mvertes authored and traefiker committed Nov 27, 2019
1 parent eef5915 commit 488e491
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
21 changes: 21 additions & 0 deletions _test/switch22.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

type T struct {
Name string
}

func f(t interface{}) {
switch ext := t.(type) {
case *T:
println("*T", ext.Name)
default:
println("unknown")
}
}

func main() {
f(&T{"truc"})
}

// Output:
// *T truc
18 changes: 8 additions & 10 deletions interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,23 +170,21 @@ func (interp *Interpreter) cfg(root *node) ([]*node, error) {
var typ *itype
if len(n.child) == 2 {
// 1 type in clause: define the var with this type in the case clause scope
switch sym, _, ok := sc.lookup(n.child[0].ident); {
case ok && sym.kind == typeSym:
typ = sym.typ
case n.child[0].kind == selectorExpr:
if typ, err = nodeType(interp, sc, n.child[0]); err != nil {
return false
}
switch {
case n.child[0].ident == "nil":
typ = sc.getType("interface{}")
default:
case !n.child[0].isType(sc):
err = n.cfgErrorf("%s is not a type", n.child[0].ident)
return false
default:
typ, err = nodeType(interp, sc, n.child[0])
}
} else {
// define the var with the type in the switch guard expression
typ = sn.child[1].child[1].child[0].typ
}
if err != nil {
return false
}
nod := n.lastChild().child[0]
index := sc.add(typ)
sc.sym[nod.ident] = &symbol{index: index, kind: varSym, typ: typ}
Expand Down Expand Up @@ -1528,7 +1526,7 @@ func isBinType(v reflect.Value) bool { return v.IsValid() && v.Kind() == reflect
// isType returns true if node refers to a type definition, false otherwise
func (n *node) isType(sc *scope) bool {
switch n.kind {
case arrayType, chanType, funcType, mapType, structType, rtypeExpr:
case arrayType, chanType, funcType, interfaceType, mapType, structType, rtypeExpr:
return true
case parenExpr, starExpr:
if len(n.child) == 1 {
Expand Down

0 comments on commit 488e491

Please sign in to comment.