変数とデータ型
Solidityの基本的なデータ型(uint、address、bool、bytes)と、スマートコントラクト内で変数を宣言・使用する方法を学びます。
「変数とデータ型」はCoddyKit上の無料Web3 & DApp Development Fundamentalsレッスンです。 これはレッスン2/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWeb3 & DApp Development Fundamentals学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Web3 & DApp Development Fundamentalsコースには全3レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Variables & Data Types: The Basics
Welcome to Lesson 2! In Solidity, just like other programming languages, we need ways to store and manage information.
This is where variables and data types come in handy. They are fundamental for building any smart contract.
- Variables: Think of them as containers that hold a specific piece of data.
- Data Types: Define what kind of data a variable can hold (e.g., numbers, text, true/false).
Storing Whole Numbers: `uint`
The uint data type is used to store unsigned integers. 'Unsigned' means they can only hold positive whole numbers (including zero).
uintcan range fromuint8(8 bits) up touint256(256 bits).uint256is the default if you just writeuint.- These are perfect for token balances, counts, or IDs.
`uint` Variable Example
Let's see how to declare and use uint variables in a simple contract. Notice how we use public to make them accessible from outside the contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyNumbers {
uint public myFavoriteNumber; // Default uint256
uint8 public smallCount; // uint with 8 bits
constructor() {
myFavoriteNumber = 42;
smallCount = 100;
}
function getFavoriteNumber() public view returns (uint) {
return myFavoriteNumber;
}
function getSmallCount() public view returns (uint8) {
return smallCount;
}
}True or False: The `bool` Type
The bool data type is simple but powerful. It can only hold one of two values: true or false.
- Booleans are essential for conditional logic, like checking if a user has permission or if a process is complete.
- By default, a
boolvariable is initialized tofalseif not explicitly set.
`bool` Variable Example
Here's a contract demonstrating how to declare and manipulate bool variables. We can set their initial state and update them later.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyFlags {
bool public isActive; // Default false, set to true in constructor
bool private isAdmin; // Only accessible within the contract
constructor() {
isActive = true;
isAdmin = false;
}
function getIsActive() public view returns (bool) {
return isActive;
}
function setIsAdmin(bool _isAdmin) public {
isAdmin = _isAdmin;
}
function checkAdmin() public view returns (bool) {
return isAdmin;
}
}Handling Accounts: The `address` Type
The address data type is unique to blockchain development. It stores a 20-byte value, which represents an Ethereum account or contract address.
- Every user wallet and smart contract on Ethereum has an
address. - There's also
address payable, which is anaddressthat can receive Ether. You'll learn more about this later! addresstypes are crucial for managing ownership, permissions, and interactions between accounts.
`address` Variable Example
This example shows how a contract can store and retrieve addresses. msg.sender is a special global variable that always refers to the address that initiated the current transaction.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract AccountManager {
address public owner; // Stores the contract deployer's address
address public lastInteractedUser;
constructor() {
owner = msg.sender; // Set owner to the deployer
}
function setLastInteractedUser() public {
lastInteractedUser = msg.sender; // Update with current caller
}
function getOwner() public view returns (address) {
return owner;
}
function getLastInteractedUser() public view returns (address) {
return lastInteractedUser;
}
}Raw Data: `bytes` & `bytesN`
When you need to store raw byte sequences, Solidity provides the bytes and bytesN types.
bytes: A dynamically-sized array of bytes. Use it when the size of the data isn't fixed.bytes1tobytes32: Fixed-size byte arrays, whereNspecifies the exact number of bytes (e.g.,bytes32for a cryptographic hash).- These are often used for cryptographic hashes, arbitrary binary data, or short strings where gas efficiency is critical.
`bytes` Variable Example
Here, we store a fixed-size hash using bytes32 and a dynamic sequence of bytes using bytes. Notice the hexadecimal literal for the hash and the hex"..." prefix for byte values.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DataStorage {
bytes32 public documentHash; // Fixed 32-byte hash
bytes public dynamicData; // Dynamic byte array
constructor() {
// Example hash (0x prefixed hex literal)
documentHash = 0x123456789012345678901234567890123456789012345678901234567890abcd;
// Example dynamic data (hex string "hello")
dynamicData = hex"68656c6c6f";
}
function updateDynamicData(bytes memory _newData) public {
dynamicData = _newData;
}
function getDocumentHash() public view returns (bytes32) {
return documentHash;
}
function getDynamicData() public view returns (bytes memory) {
return dynamicData;
}
}Data Type Challenge
Choosing the right data type is crucial for efficiency and security in smart contracts. Test your knowledge!
Variables & Types: Key Takeaways
Great job! You've learned the fundamental data types in Solidity:
uint: For positive whole numbers (balances, counts).bool: For true/false values (flags, conditions).address: For Ethereum accounts and contract addresses.bytes/bytesN: For raw, uninterpreted byte sequences (hashes, arbitrary data).
Choosing the correct data type is vital for writing efficient and secure smart contracts. Next, we'll explore how to define functions and control the flow of your contract's logic!
よくある質問
「変数とデータ型」レッスンは無料ですか?
はい。「変数とデータ型」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Web3 & DApp Development Fundamentalsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Web3 & DApp Development Fundamentalsコースには全3レッスンが含まれています。
「変数とデータ型」で何を学びますか?
Solidityの基本的なデータ型(uint、address、bool、bytes)と、スマートコントラクト内で変数を宣言・使用する方法を学びます。 ブラウザで直接実行するハンズオンコードでWeb3 & DApp Development Fundamentalsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Web3 & DApp Development Fundamentalsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのWeb3 & DApp Development Fundamentalsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/3です。
「変数とデータ型」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このWeb3 & DApp Development Fundamentalsレッスンでコードを書いて実行できますか?
はい。すべてのWeb3 & DApp Development Fundamentalsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Solidity入門
- 変数とデータ型
- 関数と制御構造