1

I have a struct

struct Shots{
    uint coverDrive;
    uint straightDrive;
    uint pull;
    uint squareCut;
}

and I used a mapping

mapping(address => Shots) public BattingSkill;

Now I want to write a function which update the value of field in the struct, but the field name is dynamic, Something like this

function skillup_Batting(string memory skill_name) public view returns(Shots memory){
    Shots memory skill = BattingSkill[msg.sender];
    skill[skill_name] += 10;
}

Whatever skillname is provided we will update only that field and the other field remain same. Is it possible to code something like this in solidity?

1 Answer 1

0
//SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

contract StackExchange {
    struct Shots{
        uint coverDrive;
        uint straightDrive;
        uint pull;
        uint squareCut;
    }
    mapping(address => Shots) public BattingSkill;

    function incrementShot(string memory shot, uint value) public {
    require(value > 0, "Value must be greater than zero.");
    require(
        keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("coverDrive")) ||
        keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("straightDrive")) ||
        keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("pull")) ||
        keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("squareCut")),
        "Invalid shot type."
    );
    Shots storage myShots = BattingSkill[msg.sender];
    if (keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("coverDrive"))) {
        myShots.coverDrive += value;
    } else if (keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("straightDrive"))) {
        myShots.straightDrive += value;
    } else if (keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("pull"))) {
        myShots.pull += value;
    } else if (keccak256(abi.encodePacked(shot)) == keccak256(abi.encodePacked("squareCut"))) {
        myShots.squareCut += value;
    }
}
}

This will work .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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