0Pricing
Web3 & DApp Development Fundamentals · บทเรียน

ฟังก์ชันและโครงสร้างควบคุม

เรียนรู้การกำหนดฟังก์ชัน ใช้ตัวปรับการมองเห็น (public, private, internal, external) และนำการควบคุมลำดับการทำงานมาใช้ (if/else, ลูป)

ฟังก์ชันและโครงสร้างควบคุม เป็นบทเรียน Web3 & DApp Development Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Web3 & DApp Development Fundamentals และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What are Functions in Solidity?

Functions are named blocks of code that perform specific tasks within your smart contract. They are fundamental for organizing your contract's logic, making it reusable, and improving readability.

Think of functions as the actions or operations your smart contract can perform, like calculating a value or updating a state variable.

Defining Your First Function

A basic function includes the function keyword, a name, optional parameters, a visibility specifier, and an optional return type. Here's a simple function that returns a greeting:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyFirstFunctions {
  function greet() public pure returns (string memory) {
    return "Hello, CoddyKit!";
  }
}

Functions with Parameters & Returns

Functions can accept inputs (called parameters) and produce outputs (return values). This allows them to perform dynamic operations based on the data you provide.

For example, a function can take two numbers and return their sum.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MathFunctions {
  function add(uint a, uint b) public pure returns (uint) {
    return a + b;
  }

  function subtract(uint a, uint b) public pure returns (uint) {
    // Ensure positive result for unsigned integers
    if (a >= b) {
      return a - b;
    } else {
      return 0;
    }
  }
}

Understanding Function Visibility

Function visibility specifies who can call a function and how. This is crucial for security and controlling access to your contract's logic and data. There are four main types:

  • public: Callable from anywhere (externally or internally).
  • private: Only callable from within the current contract.
  • internal: Callable from within the contract and derived contracts.
  • external: Only callable from outside the contract.

Public and Private Functions

public functions are the most common, allowing DApps and other contracts to interact with your contract. private functions are for internal logic that should not be exposed or called directly from outside.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract VisibilityDemo1 {
  uint private _secretNumber = 42;

  // Public function, callable by anyone
  function getSecretNumber() public view returns (uint) {
    // Can call private functions internally
    return _getSecret();
  }

  // Private function, only callable from within this contract
  function _getSecret() private view returns (uint) {
    return _secretNumber;
  }
}

Internal and External Functions

internal functions are similar to private but can also be called by contracts that inherit from the current contract. external functions can ONLY be called from outside the contract (e.g., by a user or another contract), making them gas-efficient for external-only interactions.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract VisibilityDemo2 {
  uint public counter = 0;

  // External function, only callable from outside
  function incrementExternal() external {
    // Can call internal functions
    _incrementInternal();
  }

  // Internal function, callable from within this contract
  // and derived contracts
  function _incrementInternal() internal {
    counter++;
  }
  
  // Note: Calling an external function internally
  // (e.g., this.incrementExternal()) is not allowed
  // and would result in a compile error.
}

Conditional Logic: If/Else

Control flow statements allow your contract to execute different code paths based on conditions. The if/else statement is fundamental for making decisions in your contract's logic.

  • if (condition): Executes a block of code if the condition is true.
  • else if (anotherCondition): Checks another condition if the first if was false.
  • else: Executes code if all preceding if and else if conditions were false.

If/Else Example

This example demonstrates how to use if, else if, and else to categorize a number. This is a common pattern for handling different scenarios.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ConditionalChecks {
  function checkNumber(uint num) public pure returns (string memory) {
    if (num > 100) {
      return "Number is large.";
    } else if (num > 50) {
      return "Number is medium.";
    } else {
      return "Number is small.";
    }
  }
}

Looping with `for`

Loops allow you to execute a block of code multiple times. In Solidity, the for loop is used for iterating a known number of times.

Important: Be extremely cautious with loops that involve many iterations in Solidity, as each operation costs gas. Complex or unbounded loops can lead to very high transaction fees or even run out of gas, making your transaction fail!

For Loop Example

Here's a basic for loop that sums numbers up to a given limit. For practical contracts, ensure the limit is always small and fixed, or avoid loops where gas costs could become prohibitive.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract LoopDemo {
  function sumUpTo(uint limit) public pure returns (uint) {
    // In real contracts, 'limit' should be very small
    // to avoid excessive gas costs.
    uint total = 0;
    for (uint i = 0; i < limit; i++) {
      total += i;
    }
    return total;
  }
}

Test Your Knowledge!

Which of the following statements about Solidity function visibility modifiers are TRUE?

Functions & Control Flow Summary

Great job! In this lesson, you gained essential knowledge about:

  • Defining functions to organize and modularize your contract's logic.
  • Understanding and applying public, private, internal, and external visibility modifiers to control function access.
  • Implementing conditional logic using if/else statements for decision-making.
  • Understanding the basics of for loops and the critical importance of gas considerations when using them.

These building blocks are fundamental for creating dynamic, secure, and efficient smart contracts. Next, we'll explore the Remix IDE to compile and deploy your contracts!

คำถามที่พบบ่อย

บทเรียน “ฟังก์ชันและโครงสร้างควบคุม” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ฟังก์ชันและโครงสร้างควบคุม” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Web3 & DApp Development Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ฟังก์ชันและโครงสร้างควบคุม”

เรียนรู้การกำหนดฟังก์ชัน ใช้ตัวปรับการมองเห็น (public, private, internal, external) และนำการควบคุมลำดับการทำงานมาใช้ (if/else, ลูป) คุณปฏิบัติ Web3 & DApp Development Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Web3 & DApp Development Fundamentals หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Web3 & DApp Development Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน

บทเรียน “ฟังก์ชันและโครงสร้างควบคุม” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Web3 & DApp Development Fundamentals นี้ได้ไหม

ได้ บทเรียน Web3 & DApp Development Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. บทนำสู่ Solidity
  2. ตัวแปรและชนิดข้อมูล
  3. ฟังก์ชันและโครงสร้างควบคุม
← กลับไปที่ Web3 & DApp Development Fundamentals