What is the benefit or the main reason of using "mapping" in solidity?

Viewed 157

I am a beginner in solidity. I am learning the mapping in solidity. I feel confused about why I should use mapping?

For example, here is the mapping example I saw:

contract TestContract {
    struct Buyer {
        bytes32 name;
        uint price;
    }
    mapping(address => Buyer) buyerInfo;
}

It seems trying to use an address to get Buyer info which is defined in struct. But what if I create a new address type member in struct, then it seems no need to use the mapping concept.

contract TestContract2 {
    struct Buyer {
        address addr;
        bytes32 name;
        uint price;
    }
}

Can someone explain what is the benefit or the main reason for using mapping?

1 Answers
contract TestContract {
    struct Buyer {
        bytes32 name;
        uint price;
    }

    mapping(address => Buyer) buyerInfo;
    Buyerp[] buyerInfoList; // array

    function testFunc() {
        // Map: we can access easily
        Buyer bb = buyerInfo[msg.sender];

        // Array: we need for loop to access it
        for(uint i = 0;i<buyerInfoList.length;i++) {
            if(buyerInfoList[i].address == msg.sender) {
                Buyer bb = buyerInfo[i];
            }
        }
        
        
    }
}

And, at solidity, the map's data is private, so, anyone cannot expand its data without its key.

and, if we know the key, we can access its value easily(one line).

Related