2020.코딩일지
[solidity] enum/interface (feat.솔리디티깨부수기) 본문
728x90
enum
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/*
enum: 사람이 읽을 수 있게, 사용자/개발자에 의해 정의된 상수세트 타임(uint8 = 0~255(2^8-1))
enum 이름 {
}
특정한 상태조건을 나타내어 require와 함께 쓴다.
*/
contract lec31 {
enum CarStatus{
TurnOff, //0
TurnOn, //1
Driving, //2
Stop //3
}
CarStatus public carStatus;
constructor(){
carStatus = CarStatus.TurnOff; //시동꺼진상태로 일단 시작.
}
event carCurrentStatus(CarStatus _carStatus, uint256 _carStatusInInt);
function turnOnCar() public {
require(carStatus == CarStatus.TurnOff, "To turn on, your car must be turned off");//require문은 false일때 revert가 작동한다.
//시동이꺼져있어야 true. 만약 false라면 "To turn ---" require작동!
//CarStatus.TurnOff 같은뜻 CarStatus(0)
carStatus = CarStatus(1); //CarStatus.TurnOn 같은뜻 CarStatus(1)
emit carCurrentStatus(carStatus, uint256(carStatus));
}
function DrivingCar() public {
require(carStatus == CarStatus.TurnOn, "To drive a car, your car must be turned on");
carStatus = CarStatus.Driving;
emit carCurrentStatus(carStatus, uint256(carStatus));
}
function StopCar() public {
require(carStatus == CarStatus.Driving, "To drive a car, your car must be turned on");
carStatus = CarStatus.Stop;
emit carCurrentStatus(carStatus, uint256(carStatus));
}
function turnOffCar() public {
require(carStatus == CarStatus.TurnOn || carStatus == CarStatus.Stop, "To turn off, your car must be turned on or driving");
carStatus = CarStatus.TurnOff;
emit carCurrentStatus(carStatus, uint256(carStatus));
}
function CheckStatus() public view returns(CarStatus) {
return carStatus;
}
}
interface
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/*
interface : 스컨 내에서 정의도어야할 필요한 것
1. 함수는 external로 표시
2. enum, structs 가능
3. 변수, 생성자 불가(constructor x)
*/
interface ItemInfo {
struct item {
string name;
uint256 price;
}
function addItemInfo(string memory _name, uint256 _price) external; //무조건 external!!
function getItemInfo(uint256 _index) external view returns(item memory); //무조건 external!!
}
contract lec39 is ItemInfo {
item[] public itemList; //상속받은 struct를 바로 쓰는 것.
//아래와같이 함수에 파라미터를 맞춰서 써줘야하고 override꼭 붙여야한다!
function addItemInfo(string memory _name, uint256 _price) override public {
itemList.push(item(_name, _price)); //item struct 통째로 push
}
function getItemInfo(uint256 _index) override public view returns(item memory) {
return itemList[_index];
}
}
'Block Chain' 카테고리의 다른 글
[solidity] library_SafeMath overflow (feat.솔리디티깨부수기) (0) | 2022.12.05 |
---|---|
[solidity] fallback과 receive (feat.솔리디티깨부수기) (0) | 2022.12.05 |
[solidity] payable/balance와 msg.sender (feat.솔리디티깨부수기) (0) | 2022.12.05 |
[solidity] modifier (feat.솔리디티깨부수기) (0) | 2022.12.05 |
[solidity] return/SPDX (feat.솔리디티깨부수기) (0) | 2022.12.05 |
Comments