代码之家  ›  专栏  ›  技术社区  ›  MaybeExpertDBA

如何在智能合约中将结构转换为数组?

  •  0
  • MaybeExpertDBA  · 技术社区  · 2 年前

    我会写一份关于病人病历的智能合同。我举了一个例子。但所有数据都存储在struct中。我想使用时间序列数据。据我所知,我必须使用结构数组,但我不知道如何才能做到这一点?

    你能帮我吗?

    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
        }
    }
    

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

    1 回复  |  直到 2 年前
        1
  •  1
  •   Petr Hejda    2 年前

    你可以 .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);
        }
    }
    

    请注意,如果您使用的是以太坊(Ethereum)等公共网络,则所有存储的数据都是可检索的,即使这些数据存储在非公共网络中- public 属性,查询合同存储插槽。看见 this answer 作为一个代码示例。所以,除非这只是一个学术练习,否则我真的不建议在区块链上存储健康和其他敏感数据。