매핑과 동적 배열
키-값 쌍을 위한 매핑과 유연한 데이터 목록을 위한 동적 배열 같은 복잡한 데이터 구조를 구현합니다.
매핑과 동적 배열은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Flexible Data Structures
Welcome! In Solidity, managing collections of data efficiently is key for complex smart contracts. Today, we'll dive into two powerful data structures: mappings and dynamic arrays.
These tools allow your contracts to store and retrieve information in flexible, scalable ways, essential for building robust decentralized applications.
What Are Mappings?
Think of a mapping like a dictionary or a hash table. It stores data as key-value pairs.
- You provide a unique key (like an address or an ID).
- The mapping returns the value associated with that key (like a user's balance or a name).
- Keys are not stored, only their cryptographic hash, making them very efficient for lookups.
Declaring a Mapping
To declare a mapping, you specify the key type and the value type. It's usually declared as a public state variable.
Here's how you declare a mapping to store a uint (value) for each address (key):
pragma solidity ^0.8.0;
contract MyMappings {
// A mapping from address to unsigned integer
mapping(address => uint) public balances;
// Another mapping: from uint ID to string name
mapping(uint => string) public userNames;
}Storing Data in Mappings
You can easily assign or update a value in a mapping using its key. If a key doesn't exist yet, it's created.
Let's add a function to update a user's balance:
pragma solidity ^0.8.0;
contract MyMappings {
mapping(address => uint) public balances;
function setBalance(address _user, uint _amount) public {
balances[_user] = _amount;
}
// Try calling setBalance with your address and a number,
// then check balances(yourAddress) in Remix.
}Retrieving Data from Mappings
Accessing data is straightforward: just use the key. If you try to retrieve a value for a key that hasn't been set, Solidity returns the default value for that type (e.g., 0 for uint, empty string for string, address(0) for address).
pragma solidity ^0.8.0;
contract MyMappings {
mapping(address => uint) public balances;
function setBalance(address _user, uint _amount) public {
balances[_user] = _amount;
}
function getBalance(address _user) public view returns (uint) {
return balances[_user];
}
// Deploy, call setBalance, then getBalance.
// Try getBalance for an address not yet set.
}What Are Dynamic Arrays?
A dynamic array is a list of elements of the same type, but unlike fixed-size arrays, its size can change at runtime. This makes them perfect for situations where you don't know the exact number of items upfront.
- They can grow or shrink.
- Elements are accessed by their index (starting from 0).
- They are more gas-expensive than fixed-size arrays for storage.
Declaring Dynamic Arrays
To declare a dynamic array, you simply omit the size in the square brackets. You can declare them as state variables or local variables (using memory or calldata).
Here's an example of a dynamic array of uints:
pragma solidity ^0.8.0;
contract MyArrays {
// A dynamic array of unsigned integers stored in state
uint[] public numbers;
// A dynamic array of strings (for memory use)
function createNameList() public pure returns (string[] memory) {
string[] memory names = new string[](0); // Initialize empty
return names;
}
}Adding Elements to Dynamic Arrays
The most common way to add elements to a dynamic array is using the push() method. It appends a new element to the end of the array.
array.push(): Adds a zero-initialized element.array.push(value): Adds a specific value.
pragma solidity ^0.8.0;
contract MyArrays {
uint[] public numbers;
function addNumber(uint _num) public {
numbers.push(_num); // Add _num to the end
}
function addDefault() public {
numbers.push(); // Add a 0 to the end
}
function getLength() public view returns (uint) {
return numbers.length;
}
}Accessing & Removing Elements
You can access elements by their index (starting from 0). To remove elements, you can use pop(), which removes the last element and reduces the array's length.
pragma solidity ^0.8.0;
contract MyArrays {
uint[] public data = [10, 20, 30, 40];
function getElement(uint _index) public view returns (uint) {
require(_index < data.length, "Index out of bounds");
return data[_index];
}
function removeLast() public {
data.pop(); // Removes 40
}
function getLength() public view returns (uint) {
return data.length;
}
}Advanced: Mapping of Arrays
You can combine these structures! A common pattern is a mapping where the value type is a dynamic array. This lets you associate a list of items with a key, like a user's transaction history.
Here's an example of mapping an address to a dynamic array of uints:
pragma solidity ^0.8.0;
contract UserData {
mapping(address => uint[]) public transactionHistory;
function addTransaction(address _user, uint _amount) public {
transactionHistory[_user].push(_amount);
}
function getUserTransactions(address _user) public view returns (uint[] memory) {
return transactionHistory[_user];
}
// Add a few transactions for your address, then view them.
}Check Your Understanding
Consider the following Solidity code snippet:
pragma solidity ^0.8.0;
contract DataStructures {
mapping(address => uint) public scores;
uint[] public participants;
function recordScore(address _player, uint _score) public {
if (scores[_player] == 0) {
participants.push(_player);
}
scores[_player] = _score;
}
function getParticipantCount() public view returns (uint) {
return participants.length;
}
}If recordScore(0xabc..., 100) is called, then recordScore(0xdef..., 200), and finally recordScore(0xabc..., 150), what will getParticipantCount() return?
Recap: Mappings & Dynamic Arrays
You've learned about two essential data structures in Solidity:
- Mappings: Efficient key-value stores, great for associating data with unique identifiers like addresses. They return default values for unset keys.
- Dynamic Arrays: Flexible lists that can grow or shrink in size using
push()andpop(), ideal when the number of items isn't fixed.
Mastering these will significantly enhance your ability to design robust and scalable smart contracts!
자주 묻는 질문
“매핑과 동적 배열” 강의는 무료인가요?
네 — “매핑과 동적 배열” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
“매핑과 동적 배열”에서 뭘 배우나요?
키-값 쌍을 위한 매핑과 유연한 데이터 목록을 위한 동적 배열 같은 복잡한 데이터 구조를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“매핑과 동적 배열” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.