Is there anything like a struct in dart?

That sounds like a class.

 class MyVector {
   int x;
   int y;
   MyVector(this.x, this.y);
 }

There is no simpler and more efficient way to create a name-indexed structure at runtime. For simplicity you could usually use a Map, but it's not as efficient as a real class.

A class should be at least as efficient (time and memory) as a fixed length list, after all it doesn't have to do an index bounds check.


For me, i see 2 way to do this. I will sort by best in my point of view

Class based method

Here, the approach is to encapsulate your need, in a dedicated object

Pros:

  • It's encapsultate
  • You can propose several way to access variable, depend of the need
  • You can extend functionality without break everything
  • I love it :p

Cons

  • More time spend to create class, etc.
  • Do you really need what i say in pros ?
  • Maybe weird for js people

example :

class Vector {
  int x;
  int y;

  static final String X = "x";
  static final String Y = "y";

  Vector({this.x, this.y});
  Vector.fromList(List<int> listOfCoor) {
    this.x = listOfCoor[0];
    this.y = listOfCoor[1];
  }

  // Here i use String, but you can use [int] an redefine static final member
  int operator[](String coor) {
    if (coor == "x") {
      return this.x;
    } else if (coor == "y") {
      return this.y;
    } else {
      // Need to be change by a more adapt exception :)
      throw new Exception("Wrong coor");
    }
  }
}

void main() {
  Vector v = new Vector(x: 5, y: 42);
  Vector v2 = new Vector.fromList([12, 24]);

  print(v.x); // print 5
  print(v["y"]); // print 42
  print(v2.x); // print 12
  print(v2[Vector.Y]); // print 24
}

Enum based method:

You can also defined a "enum" (actually not really implement but will be in the future version) that will contains "shortcut" to your value

Pros

  • More simple to implement
  • Is more like your example ;p

Cons

  • Less extendable
  • i think is not very pretty
  • Not OOP think

example:

class Vector {
  static final int x = 0;
  static final int y = 1;
}

void main() {
  List<int> myVector = new List(2);
  myVector[Vector.x] = 5;
  myVector[Vector.y] = 42;
}

Make your choice ;p

Tags:

Dart