From 81b01b9facb7839ba1347ff4f59edcbdfa19d782 Mon Sep 17 00:00:00 2001 From: Steven Hartland Date: Thu, 12 Feb 2015 14:35:28 +0000 Subject: [PATCH] Support go multiple return values as an array Add support for go funcs which return multiple values by returning them as an array. In the future this can be used along side destructuring assignment to provide a nice way to deal with multiple value returns e.g. [val, err] = MyGoFunc() --- reflect_test.go | 11 ++++++++--- runtime.go | 16 ++++++++++++---- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/reflect_test.go b/reflect_test.go index e4e83ad..6ae5078 100644 --- a/reflect_test.go +++ b/reflect_test.go @@ -148,9 +148,14 @@ func Test_reflectStruct(t *testing.T) { abc.FuncEllipsis("abc", "def", "ghi"); `, 3) - test(`raise: - abc.FuncReturn2(); - `, "TypeError") + test(` + ret = abc.FuncReturn2(); + if (ret && ret.length && ret.length == 2 && ret[0] == "def" && ret[1] === undefined) { + true; + } else { + false; + } + `, true) test(` abc.FuncReturnStruct(); diff --git a/runtime.go b/runtime.go index 1ac1b43..2212cfb 100644 --- a/runtime.go +++ b/runtime.go @@ -223,13 +223,21 @@ func (self *_runtime) toValue(value interface{}) Value { } out := value.Call(in) - if len(out) == 1 { - return self.toValue(out[0].Interface()) - } else if len(out) == 0 { + l := len(out) + switch l { + case 0: return Value{} + case 1: + return self.toValue(out[0].Interface()) } - panic(call.runtime.panicTypeError()) + // Return an array of the values to emulate multi value return. + // In the future this can be used along side destructuring assignment. + s := make([]interface{}, l) + for i, v := range out { + s[i] = self.toValue(v.Interface()) + } + return self.toValue(s) })) case reflect.Struct: return toValue_object(self.newGoStructObject(value))