如何在智能合约中将Struct转换为Array



我将编写一个关于患者医疗记录的智能合约。我有一个例子。但所有数据都存储在结构中。我想使用时间序列数据。据我所知,我必须使用结构的数组,但我不知道该怎么做?

你能帮我吗?

contract MedicalHistory {
enum Gender {
Male,
Female
}
uint _patientCount = 0;
struct Patient {
string name;
uint16 age;
//max of uint16 is 4096
//if we use uint8 the max is uint8
string telephone;
string homeAddress;
uint64 birthday; //unix time
string disease; //disease can be enum
uint256 createdAt; // save all history
Gender gender;
}
mapping(uint => Patient) _patients;
function Register(
string memory name,
uint16 age,
string memory telephone,
string memory homeAddress,
uint64 birthday,
string memory disease,
// uint256 createdAt,
Gender gender
}
}

这是我的智能合约中的代码片段。。如何将结构转换为数组?

您可以将.push()放入存储阵列中,从而有效地添加新项。

我简化了代码示例,只是为了更容易看到实际的数组操作:

pragma solidity ^0.8;
contract MedicalHistory {
struct Patient {
string name;
uint16 age;
}
Patient[] _patients;
function Register(
string memory name,
uint16 age
) external {
Patient memory patient = Patient(name, age);
_patients.push(patient);
}
}

请注意,如果您使用的是以太坊等公共网络,则通过查询合同存储槽,即使存储在非public属性中,也可以检索所有存储的数据。有关代码示例,请参阅此答案。因此,除非这只是一项学术活动,否则我真的不建议将健康和其他敏感数据存储在区块链上。

最新更新