【问题标题】:How to query a struct by multiple attributes in Solidity?如何在 Solidity 中通过多个属性查询结构?
【发布时间】:2018-11-07 06:15:26
【问题描述】:

假设我有以下合同:

contract UserContract {
    struct User {
        address walletAddress;
        string organisation;
        string fName;
        string lName;
        string email;
        uint index;
    }
    mapping(address => User) private users;
    address[] private userIndex;
}

我知道如何编写一个返回与给定address 对应的用户信息的函数,但我还想编写一个可以通过User 的电子邮件地址获取用户信息的函数。

这是如何工作的?我唯一的选择是为这个将User 结构映射到字符串的用例创建单独的映射吗?如果是这样,这是否意味着该结构被存储了两次?还是只存储对该结构的引用?

谢谢!

【问题讨论】:

  • 你可以使用for循环,但它需要更多的处理,但for循环可以是一个解决方案

标签: ethereum solidity truffle


【解决方案1】:

如果您想通过地址或电子邮件进行搜索(即,不是复合键),那么是的,最简单的选择是使用两个不同的mappings。但是,struct 值作为副本存储(有关如何存储映射的信息,请参阅 this)。

为避免为复杂的structs 存储额外的存储空间,请将其存储在一个数组中并使用mapping 值的索引。

contract UserContract {
    struct User {
        address walletAddress;
        string organisation;
        string fName;
        string lName;
        string email;
        uint index;
    }
    User[] users;
    mapping(address => uint256) private addressMap;
    mapping(string => uint256) private emailMap; // Note this must be private if you’re going to use `string` as the key. Otherwise, use bytes32
    address[] private userIndex;
}

【讨论】:

  • 像魅力一样工作!谢谢
猜你喜欢
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多