"structure has extra field" 错误背后的原因是什么

What's the reason behind "structure has extra field" error

考虑这段代码:

var t: {a: Int} = {a:100, b:200};

它没有编译错误:{ b : Int, a : Int } has extra field b

但是这段代码编译得很好:

class Foo {
    public var a: Int = 100;
    public var b: Int = 200;
    public function new() {}
}
...
var t: {a: Int} = new Foo();

为什么第一种情况被禁止?

如果有一些额外的字段,会出现什么问题?如果出现问题,为什么在第二种情况下允许它们。

我认为这里有答案:https://groups.google.com/forum/#!topic/haxelang/KQO4eFUb-N0

尼古拉斯解释道:

In your example both are considered constant values, and then an error is printed because it has extra fields. That error was added in order to enable code cleanup when you remove a field from a required structure : it will tell you every place this field is still passed (when passing a constant, which happen most of the time).

I agree the error is a bit misleading when making simple tests such as your own, but in actual code it rarely occur.

之前已经对此进行了讨论 in this issue,其中 Nicolas 对当前行为给出了以下推理:

The idea is that constant structures are not allowed to be reduced. This allows for instance to check for the following:

function foo(o:{?x:Int,?y:Int}) {
}
var pt = { x: 0, yy : 1 }; // typo
foo(pt); // goes unnoticed

Also, it will gives error if you modify the signature of foo, for instance by removing a field.

但是,该问题仍未解决,看起来可能会更改行为以在将来允许此操作。