不要说什么用传引用或者指针实现,那也是返回一个值
<code class="language-c"><span class="kt">unsigned</span> <span class="n">c</span> <span class="o">=</span> <span class="n">a</span><span class="o">/</span><span class="n">b</span><span class="p">;</span>
<span class="kt">unsigned</span> <span class="n">r</span> <span class="o">=</span> <span class="n">a</span><span class="o">%</span><span class="n">b</span><span class="p">;</span>
</code>
没为啥。图简单呗<code class="language-text">g(f(x))
h(f(y))
</code>
go支持返回多个值,函数签名里写的是多个类型,不是tuple之类,实现也和lua的类似,不需要额外的包装,不是语法糖(因为并不是返回一个struct,没有对应的无糖做法)。所以这和静态类型、脚本语言什么的没有关系,只是设计理念不同而已。<code class="language-go"><span class="kn">package</span> <span class="nx">main</span>
<span class="kd">func</span> <span class="nx">main</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">fn</span> <span class="o">:=</span> <span class="kd">func</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span> <span class="nx">b</span> <span class="kt">int</span><span class="p">)</span> <span class="p">(</span><span class="kt">int</span><span class="p">,</span> <span class="kt">int</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="nx">a</span><span class="p">,</span> <span class="nx">b</span>
<span class="p">}</span>
<span class="nx">fn</span><span class="p">(</span><span class="nx">fn</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="p">}</span>
</code>
认为 @yf zpy说的是语法糖的.[a, b, c] = fun()
编译后的js代码:
<code class="language-text">var a, b, c, _ref;
_ref = fun(), a = _ref[0], b = _ref[1], c = _ref[2];
</code>
返回多值?只不过是返回元组再赋值解构的语法糖而已。C++照样能做:
<code class="language-text">#include <tuple>
#include <string>
#include <stdexcept>
using namespace std;
tuple<double char string> get_student(int id)
{
if (id == 0) return make_tuple(3.8, 'A', "Lisa Simpson");
if (id == 1) return make_tuple(2.9, 'C', "Milhouse Van Houten");
if (id == 2) return make_tuple(1.7, 'D', "Ralph Wiggum");
throw invalid_argument("id");
}
int main()
{
double gpa1;
char grade1;
string name1;
tie(gpa1, grade1, name1) = get_student(1);
return 0;
}
</double></stdexcept></string></tuple></code>