1. 값형 데이터형
1.1. INT / UINT
uint 의 약자입니다 부호 없는 정수, 그리고 다음 중에서 크기를 선택할 수 있습니다 uint8 ~에 uint256
uint8~부터0~에2 × 8 - 1uint16~부터0~에2 ** 16 - 1
...uint256~부터0~에2 × 256 - 1
uint8 public u8 = 1;
uint256 public u256 = 456;
uint public u = 123; // uint는 uint256의 약어입니다
int 의 약자입니다 정수, 그리고 다음 중에서 크기를 선택할 수 있습니다 int8 ~에 int256
int8~부터-2 × 7~에2 × 7 - 1int16~부터-2 × 15~에2 ** 15 - 1...int128~부터-2 × 127~에2 × 127 - 1int256~부터-2 × 255~에2 × 255 - 1
int8 public i8 = -1;
int256 public i256 = 456;
int public i = -123; // int는 int256의 약어입니다int 및 uint 연산자:
- Comparisons: <=, <, ==, !=, >=, > (returns
bool) - 비트 연산: &, |, ^ (비트별 배타적 논리합), ~ (비트별 부정)
- Shifts: << (left shift), >> (right shift)
- 더하기, 빼기, 곱하기:
+,-,부정적 -(예를 들어부호 있는 정수),*,/,%(모듈로),**(제곱)
~의 경우 정수 변수 X의 경우, 다음을 사용할 수 있습니다 type(X).min 그리고 type(X).max 해당 유형의 최소값과 최대값을 각각 확인하려면
// int 형의 최소값과 최대값:
int public minInt = type(int).min;
int public maxInt = type(int).max;
// uint 형의 최소값과 최대값:
uint public minUint = type(uint).min;
uint public maxUint = type(uint).max;1.2. BOOL
bool ~을 의미한다 부울 그리고 다음 두 가지 값을 가질 수 있습니다. 참 그리고 아니요
bool public trueVar = true;
bool public falseVar = false;1.3. 운영자:
!(논리적 부정)&&(논리적 결합, “그리고”)||(논리적 합집합, “또는”)==(평등)!=(불평등)
운영자 || 그리고 && 일반적인 단락 연산 규칙을 적용합니다. 즉, 다음 식에서 f(x) || g(y), 만약 f(x) 다음과 같이 계산됩니다 참, g(y) 부작용이 있을 수 있더라도 평가되지 않습니다.
1.4. 주소
주소Solidity의 특수 데이터 유형으로, Kaia 계정 주소의 20바이트(크기)를 저장할 수 있습니다수취인 주소~와 비슷하다주소하지만 메서드 2개를 더 추가합니다이체그리고보내기
공개 주소 exampleAddress = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
지급 대상 주소 public examplePayableAddress = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;1.5. 바이트
Solidity에서 byte 데이터형은 바이트 시퀀스를 나타냅니다. Solidity에는 두 가지 유형의 바이트가 있습니다:
- 고정 길이의 바이트 배열
- 동적 크기의 바이트 배열.
Solidity에서 ‘bytes’라는 단어는 바이트 단위의 동적 배열을 의미합니다. 기본적으로 byte[]를 나타냅니다.
bytes1 a = 0xb5; // [10110101]
bytes1 b = 0x56; // [01010110]
바이트 c = "abc"; // [01100001, 01100010, 01100011]1.6. 기본값
값이 할당되지 않은 선언된 변수에는 기본값이 적용됩니다.
bool public defaultBool; // false
uint public defaultUint; // 0
int public defaultInt; // 0
address public defaultAddr; // 0x0000000000000000000000000000000000000000
바이트1 public defaultByte; // 0x001.7. 계약
계약 Solidity에서 계약을 선언하는 데 사용됩니다.
contract HelloWorld {}계약 키워드를 사용하여 다른 계약에서 상속받을 수도 있습니다 이다
계약 차량: 메르세데스 {}1.8. ENUM
열거형 는 솔리디티에서 사용자 정의 타입을 생성하는 한 가지 방법입니다. 이 타입은 모든 정수형과 명시적으로 상호 변환이 가능하지만, 암시적 변환은 허용되지 않습니다. 정수형에서 명시적으로 변환할 경우 런타임에 해당 값이 열거형의 범위 내에 있는지 확인하며, 이로 인해 패닉 오류 그렇지 않으면. 열거형 최소 한 개의 요소를 포함해야 하며, 선언 시 기본값은 첫 번째 요소입니다. 열거형에는 256개 이상의 요소를 가질 수 없습니다.
데이터 표현 방식은 다음과 같습니다. 열거형 C 언어에서: 옵션은 0부터 시작하는 연속된 부호 없는 정수 값으로 표시됩니다.
사용 type(열거형명).min 그리고 type(열거형명).max 주어진 열거형의 최소값과 최대값을 구할 수 있습니다.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Enum {
// Enum representing shipping status
enum Status {
Pending,
Shipped,
Accepted,
Rejected,
Canceled
}
// Default value is the first element listed in
// definition of the type, in this case "Pending"
Status public status;
// Returns uint
// Pending - 0
// Shipped - 1
// Accepted - 2
// Rejected - 3
// Canceled - 4
function get() public view returns (Status) {
return status;
}
// Update status by passing uint into input
function set(Status _status) public {
status = _status;
}
// You can update to a specific enum like this
function cancel() public {
status = Status.Canceled;
}
// delete resets the enum to its first value, 0
function reset() public {
delete status;
}
}1.9. 유형
사용자 정의 값 유형을 사용하면 기본 값 유형 위에 비용이 전혀 들지 않는 추상화를 생성할 수 있습니다. 이는 별칭과 유사하지만, 더 엄격한 유형 요구 사항을 따릅니다.
사용자 정의 값 형식은 다음을 사용하여 정의됩니다. C형은 V형입니다, 그곳에서 C 새로 도입된 유형의 이름이며 V 반드시 내장 값형(“기본 유형”)이어야 합니다
// SPDX-License-Identifier: GPL-3.0
pragma solidity^0.8.8;
// 사용자 정의 값 유형을 사용하여 18자리 십진수, 256비트 폭의 고정 소수점 유형을 표현합니다.
type UFixed256x18 is uint256;1.10. 함수
함수 Solidity에서 함수를 선언할 때 키워드가 사용됩니다.
우리는 다음을 선언할 수 있습니다 함수 다음과 같이:
contract Counter {
uint public count;
// Function to view count variable
function get() public view returns (uint) {
return count;
}
}2. 참조형
2.1. 데이터 저장 위치
변수는 다음 단어를 사용하여 선언합니다 저장, 기억 또는 호출 데이터 데이터를 저장할 위치를 지정하려면.
저장- 변수는 상태 변수입니다(블록체인에 저장됨).기억- 변수는 메모리에 저장되며,함수실행 중입니다호출 데이터- 함수에 전달된 데이터를 포함하는 전용 데이터 저장소
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract DataLocations {
uint storage varStorage
uint memory varMemory
uint calldata varCallData
}2.2. 배열
배열 이는 동일한 형식의 값 요소들이 결합된 것으로, 다음과 유사합니다. 목록 파이썬에서 그리고 배열 에서 자바스크립트.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Array {
// Several ways to initialize an array
uint[] public arr;
uint[] public arr2 = [1, 2, 3];
// Fixed sized array, all elements initialize to 0
uint[10] public myFixedSizeArr;
function get(uint i) public view returns (uint) {
return arr[i];
}
// Solidity can return the entire array.
// But this function should be avoided for
// arrays that can grow indefinitely in length.
function getArr() public view returns (uint[] memory) {
return arr;
}
function push(uint i) public {
// Append to array
// This will increase the array length by 1.
arr.push(i);
}
function pop() public {
// Remove last element from array
// This will decrease the array length by 1
arr.pop();
}
function getLength() public view returns (uint) {
return arr.length;
}
function remove(uint index) public {
// Delete does not change the array length.
// It resets the value at index to it's default value,
// in this case 0
delete arr[index];
}
function examples() external {
// create array in memory, only fixed size can be created
uint[] memory a = new uint[](5);
}
}
2.3. 구조체
구조체 프로그래머가 다양한 형식의 변수들을 하나의 이름으로 묶어 편리하게 사용할 수 있도록 선언하는 데이터 형식입니다. 계약.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Todos {
struct Todo {
string text;
bool completed;
}
// An array of 'Todo' structs
Todo[] public todos;
function create(string calldata _text) public {
// 3 ways to initialize a struct
// - calling it like a function
todos.push(Todo(_text, false));
// key value mapping
todos.push(Todo({text: _text, completed: false}));
// initialize an empty struct and then update it
Todo memory todo;
todo.text = _text;
// todo.completed initialized to false
todos.push(todo);
}
// Solidity automatically created a getter for 'todos' so
// you don't actually need this function.
function get(uint _index) public view returns (string memory text, bool completed) {
Todo storage todo = todos[_index];
return (todo.text, todo.completed);
}
// update text
function updateText(uint _index, string calldata _text) public {
Todo storage todo = todos[_index];
todo.text = _text;
}
// update completed
function toggleCompleted(uint _index) public {
Todo storage todo = todos[_index];
todo.completed = !todo.completed;
}
}3. 매핑 유형
지도 작성
매핑 ~를 사용하여 ~를 만들 수 있습니다 해시맵 (~와 비슷하게) 사전 에서 파이썬) 1과 1 사이 유형 다른 곳으로 유형.
참고:
~을(를) 만들 때매핑, 모두키동시에 존재한다. 즉,
예를 들어, 다음을 생성합니다mapping(address => uint256) addressToValue;. 아직 아무것도 설정하지 않으셨다면키그리고값그러면 모두주소입력하신 내용은 다음의 기본값을 반환합니다.uint256이는 0입니다.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Mapping {
// Mapping from address to uint
mapping(address => uint) public myMap;
function get(address _addr) public view returns (uint) {
// Mapping always returns a value.
// If the value was never set, it will return the default value.
return myMap[_addr];
}
function set(address _addr, uint _i) public {
// Update the value at this address
myMap[_addr] = _i;
}
function remove(address _addr) public {
// Reset the value to the default value.
delete myMap[_addr];
}
}
contract NestedMapping {
// Nested mapping (mapping from address to another mapping)
mapping(address => mapping(uint => bool)) public nested;
function get(address _addr1, uint _i) public view returns (bool) {
// You can get values from a nested mapping
// even when it is not initialized
return nested[_addr1][_i];
}
function set(address _addr1, uint _i, bool _boo) public {
nested[_addr1][_i] = _boo;
}
function remove(address _addr1, uint _i) public {
delete nested[_addr1][_i];
}
}4. 간편한 저장
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleStorage {
// Declare a variable to store the name of the maintainer
string public maintainerName = "zxstim";
// Declare the version of the contract
uint8 public version = 1;
// Declare an address to receive donation
address public donationAddress = 0xe3d25540BA6CED36a0ED5ce899b99B5963f43d3F;
// Declare a Person type to store information of a person
struct Person {
string name; // name
uint8 age; // age
bool overEighteen; // Over eighteen?
address uuid; // UUID
uint256 assetValue; // asset value
int256 debtValue; // debt value
}
Person[] private listOfPeople; // this syntax means creating an array to store Person named listOfPeople
mapping(address => Person) uuidToPerson; // this syntax means creating a mapping from address to Person named uuidToPerson
// this function will store the information of a new person with name, age, overEighteen, assetValue, debtValue
function storePerson(string memory _name, uint8 _age, bool _overEighteen, uint256 _assetValue, int256 _debtValue) public returns (Person memory person) {
_assetValue *= 1e18; // Convert asset value to wei unit
_debtValue *= 1e18; // Convert debt value to wei unit
// Add information of the new person to the listOfPeople array
listOfPeople.push(Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue}));
// Add information of the new person to the uuidToPerson mapping
uuidToPerson[msg.sender] = Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue});
return Person({name: _name, age: _age, overEighteen: _overEighteen, uuid: msg.sender, assetValue: _assetValue, debtValue: _debtValue});
}
// this function will retrieve the information of a person based on the address
function retrievePerson(address _address) public view returns (Person memory person) {
return uuidToPerson[_address];
}
}