Solidity

Solidity:如何繼承結構以創建新結構?

  • November 8, 2021

有沒有辦法在定義新結構時繼承先前定義的結構(類似於 C++ 中的類)?

我正在尋找這樣的東西:

struct Person {
   bytes32 name;
   uint256 age;
}

struct Doctor : Person {
  bytes32 specialty;
  uint256 years_experience;
}

這將定義醫生也有名字和年齡。

它在可靠性方面的工作方式略有不同,您需要在結構中使用結構。例子:

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

contract Example {

 struct Person {
     bytes32 name;
     uint256 age;
 }

 struct Doctor {
    Person person;
    bytes32 specialty;
    uint256 years_experience;
 }

 mapping (address => Doctor) mapAddrToDoc;

 function addDoctor(bytes32 name, uint256 age, bytes32 specialty, uint256 years_experience) public {
     Doctor memory doc = Doctor(Person(name, age), specialty, years_experience);
     mapAddrToDoc[msg.sender] = doc;
 }

 function getNameOfDoc(address addr) public view returns (bytes32){
     return mapAddrToDoc[addr].person.name;
 }
}

引用自:https://ethereum.stackexchange.com/questions/113132