0Pricing
Blockchain Smart Contracts with Solidity · 강의

상태 변수와 저장소 배치

저장소, 메모리, 호출 데이터의 차이와 상태 변수가 블록체인에 지속되는 방식을 이해합니다.

상태 변수와 저장소 배치은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What are State Variables?

Welcome to understanding how data lives on the blockchain! In Solidity, state variables are special variables whose values are permanently stored in the contract's storage on the blockchain.

Think of them as the persistent memory of your smart contract. Their values are saved even after a function finishes executing and across different transactions.

Data Locations in Solidity

Solidity uses different data locations to manage where information is stored during contract execution. These locations have big impacts on gas costs and how your variables behave.

  • storage: Permanent state on the blockchain.
  • memory: Temporary data for function execution.
  • calldata: Read-only data for external function arguments.

Deep Dive into `storage`

Variables declared at the contract level (outside of any function) are automatically assigned to storage. These are your contract's state variables.

Data in storage is expensive to modify because every change is written to the blockchain, making it permanent and immutable (in the sense of its history).

`storage` in Action

This contract stores a number in a state variable. Notice how myNumber keeps its value between calls to setNumber and getNumber.

pragma solidity ^0.8.0;

contract StorageExample {
    uint public myNumber; // This is a state variable, lives in storage

    function setNumber(uint _num) public {
        myNumber = _num;
    }

    function getNumber() public view returns (uint) {
        return myNumber;
    }
}

Understanding `memory`

memory is a temporary data location. It's used for variables that exist only during a function call and are discarded once the function execution completes.

It's cheaper than storage for temporary data, making it ideal for arrays, strings, or structs that are created and used within a single function.

`memory` in Action

This function creates a string in memory, modifies it, and returns it. The string only exists for the duration of the function call.

pragma solidity ^0.8.0;

contract MemoryExample {
    function greet(string memory _name) public pure returns (string memory) {
        string memory greeting = "Hello, ";
        // Use abi.encodePacked for simple string concatenation
        return string(abi.encodePacked(greeting, _name, "!"));
    }
}

Introducing `calldata`

calldata is a special read-only data location used exclusively for external function parameters. It's even cheaper than memory because data is not copied into memory, just referenced.

You cannot modify calldata. It's typically used for large data passed to external functions, saving gas by avoiding copies.

`calldata` in Action

This external function takes a string as calldata. Notice it's read-only and efficient for external calls.

pragma solidity ^0.8.0;

contract CalldataExample {
    // This function can only be called externally
    function processData(bytes calldata _data) external pure returns (uint) {
        // You cannot modify _data directly, but can read its properties
        return _data.length; // Returns the byte length of the data
    }

    // Another example returning calldata directly
    function echoString(string calldata _message) external pure returns (string calldata) {
        return _message;
    }
}

Comparing Data Locations

Choosing the right data location is crucial for gas optimization and correct contract behavior:

  • Storage: Permanent, expensive, contract state.
  • Memory: Temporary, cheaper, within-function variables.
  • Calldata: Read-only, cheapest, external function arguments.

Always use the most restrictive and cheapest option possible.

How Storage is Organized

Solidity packs state variables into 256-bit (32-byte) storage slots to save space and gas. Smaller types (like uint8, bool) can be packed together into a single slot.

However, this packing can be complex and depends on the order of variable declarations. Understanding it helps optimize gas costs, especially with structs and arrays.

Data Location Quiz

Which data location is used for permanent storage of a contract's state variables on the blockchain?

Summary of Data Locations

Great job! You've learned about the fundamental data locations in Solidity: storage, memory, and calldata.

  • State variables live in storage, making them persistent.
  • memory is for temporary data during function execution.
  • calldata is for efficient, read-only external function arguments.

Understanding these helps you write more efficient and correct smart contracts. Next, we'll explore complex data structures like Mappings and Dynamic Arrays!

자주 묻는 질문

“상태 변수와 저장소 배치” 강의는 무료인가요?

네 — “상태 변수와 저장소 배치” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 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개 중 1번째 강의입니다.

“상태 변수와 저장소 배치” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 상태 변수와 저장소 배치
  2. 매핑과 동적 배열
  3. 이벤트 및 로깅 데이터
  4. 스토리지 슬롯과 가스 최적화
← Blockchain Smart Contracts with Solidity(으)로 돌아가기