fix: convert literal nil to interface types

This commit is contained in:
Marc Vertes
2020-03-18 10:34:05 +01:00
committed by GitHub
parent ca68c6cd95
commit daaeac6e2c
3 changed files with 32 additions and 6 deletions

12
_test/interface27.go Normal file
View File

@@ -0,0 +1,12 @@
package main
import "fmt"
var errs = map[int]error{0: nil}
func main() {
fmt.Println(errs)
}
// Output:
// map[0:<nil>]

12
_test/interface28.go Normal file
View File

@@ -0,0 +1,12 @@
package main
import "fmt"
var errs = []error{nil}
func main() {
fmt.Println(errs)
}
// Output:
// [<nil>]

View File

@@ -2393,14 +2393,16 @@ func recv2(n *node) {
} }
func convertLiteralValue(n *node, t reflect.Type) { func convertLiteralValue(n *node, t reflect.Type) {
// Skip non-constant values, undefined target type or interface target type. switch {
if !(n.kind == basicLit || n.rval.IsValid()) || t == nil || t.Kind() == reflect.Interface { case n.typ.cat == nilT:
return // Create a zero value of target type.
} n.rval = reflect.New(t).Elem()
if n.rval.IsValid() { case !(n.kind == basicLit || n.rval.IsValid()) || t == nil || t.Kind() == reflect.Interface:
// Skip non-constant values, undefined target type or interface target type.
case n.rval.IsValid():
// Convert constant value to target type. // Convert constant value to target type.
n.rval = n.rval.Convert(t) n.rval = n.rval.Convert(t)
} else { default:
// Create a zero value of target type. // Create a zero value of target type.
n.rval = reflect.New(t).Elem() n.rval = reflect.New(t).Elem()
} }