I’d like to make a simple anonymous structure type, and then make an array of objects of that type, like so:
class Main {
public static function main() {
typedef SomeType {
var n:Int;
var s:String;
var f:Float;
};
var arr:Array<SomeType> = [];
arr.push({4, "this", 1.1});
arr.push({5, "that", 1.2});
arr.push({6, "other", 0.9});
for (elem in arr) { trace(elem); }
}
}
But that fails with:
src/Main.hx:3: characters 9-16 : Expected }
What’s my mistake here? (I think I may be misunderstanding the point of a typedef anon struct.)
How do you use typedef and an anonymous struct to make an array of them?
typedef SomeType {
var n:Int;
var s:String;
var f:Float;
};
class Main {
public static function main() {
var arr:Array<SomeType> = [];
arr.push({4, "this", 1.1});
arr.push({5, "that", 1.2});
arr.push({6, "other", 0.9});
for (elem in arr) { trace(elem); }
}
}
typedef SomeType = {
var n:Int;
var s:String;
var f:Float;
};
class Main {
public static function main() {
var arr:Array<SomeType> = [];
arr.push({4, "this", 1.1}); // <-- Error: "Missing ;" after the 4
arr.push({5, "that", 1.2});
arr.push({6, "other", 0.9});
for (elem in arr) { trace(elem); }
}
}
Ah. Ok. Thanks. I see that the purpose of the typedef is to allow me to set the type of array when I declare it.
var arr:Array<SomeType> = [];
// rather than
var arr = []; // and letting the compiler figure it out later.
I think part of why I was confused was because I’m used to seeing a type after a colon (ex. n: Int, not n: 5). That is, I expected “:” to always mean, “with a type of”, but I see that this is one place where that’s not the case. (Ah, another is the colon in a switch/case.)
Oh, maybe a good rule of thumb is: with types, always leave out the space (n:Int), but with anon structs (and switch/case), include the space (n: 5). That makes them a little bit more visually distinct.