1

Suppose you had two structs,

struct Weapon {
    int atk;
    int duration;
}
struct Armor {
    int def;
    int duration;
}

then, how do you write this:

struct Equipment {
    /* can be either an Weapon or an Armor */
}
function atkOrDef(Equipment equip) returns(int) {
    /* returns the atk if an Weapon, or the def if an Armor */
}

If that isn't possible, how would you do that?

2

Solidity does have inheritance. You could define a class Equipment that is extended by classes Weapon and Armor (you have to define them separately. Then add an attribute that uniquely distinguishes from Weapon and Equipment (an integer with a predefined value). Then you could use this attribute in the atkOrDef (call a getter method of the attribute) and use it to determine if Equipment equip is either Weapon or Armor.

Something along the lines of:

contract Equipment {
    uint atk;
    uint duration;
    // Define an attribute that uniquely distinguishes Weapon from
    // Armor
    uint unique;

    function Equipment(uint atk_param, uint duration_param) {
       atk = atk_param;
       duration = duration_param;
    }

    // getter method for the attribute
    function getWeaponOrArmor() constant public (uint) {
       return unique;
    }
}

contract Weapon is Equipment {

    // This is the constructor of Weapon
    function Weapon(uint atk, uint duration) public {
        unique = 0;
    }

}

Define Armor similarly:

contract Armor is Equipment {

// This is the constructor of Weapon
function Armor(uint atk, uint duration) public {
    unique = 1;
}

}

Next, in the atkOrDef function check the attribute against the respective values:

function atkOrDef(Equipment equip) returns(int) {
    if(equip.getWeaponOrArmor()) return 0;
    else 1;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.