samedi 8 juin 2019

Golang alternative to Object's getter/setter in javascript

Lets say I have two struct data types (default and new) that represents same object. I need preserve default one for compatibility reasons. The conversion(adaptor) is memory and cpu expensive so I would like to call it only when necessary.

There is getter/setter approach in javascript. I found getter/setter answers related only to interfaces and theirs methods like GetName() etc. The point is that this old data type is accessed via field name and not method name (like GetObject()). I wrote js example of what I mean so my question: is there Golang alternative for the code bellow? Thanks

var oldObject = {
  oldDatetime: new Date().toISOString()
}

var newObject = {
  _datetime: new Date(),
  _oldDatetime: "",
  get datetime() {
    return this._datetime;
  },
  set datetime(dt) {
    // change of datetime value resets oldDatetime 
    this._oldDatetime = "";
    this._datetime = dt;
  },
  get oldDatetime() {
    if (!this._oldDatetime) {
      this._oldDatetime = this._datetime.toISOString();
    }
    return this._oldDatetime;
  },
  set oldDatetime(s) {
    this._datetime = new Date(s);
  }
};

console.log('datetime: ', newObject.datetime);
console.log('internal _oldDatetime value: ', newObject._oldDatetime || 'undefined');
console.log('oldDatetime getter called: ', newObject.oldDatetime);
console.log('internal _oldDatetime value: ', newObject._oldDatetime || 'undefined');

Aucun commentaire:

Enregistrer un commentaire