Array of objects of typedef anonymous structure type

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?

You can’t declare type (typedef in your case) in a type (class in your case).

Thanks, Kevin.

Ok. I moved it outside class Main:

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); }
    }
}

but got a similar error:

src/Main.hx:1: characters 18-19 : Unexpected {

You missed a = after typedef SomeType

1 Like

Thanks, Kevin. Almost there! Still fails:

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); }
    }
}

Am I instantiating those objects incorrectly?

Hej !

You have to do arr.push( { n : 4, s : "this", f : 1.1 } )

1 Like

You can found out more about anonymous structure in the manual Anonymous Structure - Haxe - The Cross-platform Toolkit.

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.

You can also just use haxe-formatter with format on save, then it just happens magically. :slight_smile:

2 Likes