Solidity 데이터 형식과 변수
Solidity의 값 형식과 참조 형식, 변수 선언 및 초기화 방법을 학습합니다.
Solidity 데이터 형식과 변수은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Data Types: The Basics
Welcome to Solidity! Just like in any programming language, understanding data types is fundamental.
Data types tell Solidity what kind of information a variable will hold. This helps the Ethereum Virtual Machine (EVM) efficiently manage memory and prevent common errors.
Value Types Explained
Value types are the simplest data types. When you assign a value type variable or pass it to a function, a copy of its data is made.
Think of it like giving someone a photo – they get their own copy, and changes to their copy don't affect yours. They are stored directly in the variable's location.
Booleans and Integers
Let's start with common value types:
bool: Holdstrueorfalse.uint: Unsigned integers (non-negative numbers).uint256or simplyuintis the default.int: Signed integers (positive or negative numbers).int256orintis the default.
Try running this simple contract to see them in action:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyNumbers {
bool public isActive = true;
uint public quantity = 100;
int public temperature = -5;
function getStatus() public view returns (bool) {
return isActive;
}
function getQuantity() public view returns (uint) {
return quantity;
}
function getTemperature() public view returns (int) {
return temperature;
}
}The Address Type
The address type is crucial in Solidity. It's a 20-byte value representing an Ethereum account or a contract on the blockchain.
address: Can hold any Ethereum address.address payable: Can also hold an Ethereum address, but specifically one that can receive Ether.
Here's how you might store a contract owner's address:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleWallet {
address public owner;
constructor() {
owner = msg.sender; // The address that deployed this contract
}
function getOwner() public view returns (address) {
return owner;
}
}Fixed-Size Byte Arrays
Solidity also has fixed-size byte arrays: bytes1 up to bytes32.
These are useful for storing small, fixed-length sequences of raw bytes, like cryptographic hashes or short identifiers. They are more efficient than dynamic arrays for known sizes.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DataStore {
bytes32 public documentHash;
constructor() {
// Example: A hash of some document content
documentHash = 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef;
}
function getDocumentHash() public view returns (bytes32) {
return documentHash;
}
}Reference Types Explained
Unlike value types, reference types don't store the data directly. Instead, they store a reference (a memory address) to where the data is located.
This means if you assign a reference type variable, both variables point to the same data. Changes made through one variable will be visible through the other.
Strings for Text
The string type is used for text data. It's a dynamic array of bytes that stores UTF-8 encoded characters.
Because its size can change, string is considered a reference type. You'll often see memory or calldata used with strings in function parameters or return types.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Greeter {
string public currentMessage = "Hello, CoddyKit!";
function setMessage(string memory _newMessage) public {
currentMessage = _newMessage;
}
function getMessage() public view returns (string memory) {
return currentMessage;
}
}Dynamic Bytes and Arrays
Solidity offers dynamic data structures:
bytes: A dynamic-sized byte array. Similar tostringbut for raw byte data.- Arrays (
T[]orT[k]): Can hold a sequence of elements of the same typeT. They can be fixed-size (T[k], wherekis the length) or dynamic (T[]).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DataCollection {
bytes public rawData = hex"1a2b3c"; // Dynamic bytes
uint[] public dynamicNumbers; // Dynamic array of uints
bool[2] public fixedBooleans = [true, false]; // Fixed-size array
constructor() {
dynamicNumbers.push(10);
dynamicNumbers.push(20);
}
function getRawData() public view returns (bytes memory) {
return rawData;
}
function getDynamicNumbersCount() public view returns (uint) {
return dynamicNumbers.length;
}
}Custom Data with Structs
Sometimes, you need to group related data together. That's where structs come in handy!
A struct allows you to define your own custom data type by combining several variables of different types. Think of it like creating a blueprint for a record.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract UserProfile {
struct User {
uint id;
address userAddress;
string name;
bool isActive;
}
User public adminUser;
constructor() {
adminUser = User(1, msg.sender, "Alice", true);
}
function getAdminName() public view returns (string memory) {
return adminUser.name;
}
}Declaring & Initializing
Declaring a variable is straightforward: DataType visibility variableName;
If you don't explicitly initialize a variable, Solidity assigns a default value:
bool:falseuint/int:0address:0x00...00(zero address)string/bytes/arrays: Empty value
It's good practice to initialize variables explicitly when they're declared.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VariableLife {
// Declared without explicit initialization (gets default values)
uint public defaultBalance;
bool public defaultStatus;
// Declared and initialized
uint public initialBalance = 1000;
string public greeting = "Hello";
function getDefaults() public view returns (uint, bool) {
return (defaultBalance, defaultStatus);
}
}Data Type Challenge
Test your knowledge on Solidity data types!
Lesson Recap
Great job! In this lesson, you've learned about the fundamental data types in Solidity:
- Value types (e.g.,
bool,uint,address, fixedbytesX) store data directly and are copied on assignment. - Reference types (e.g.,
string, dynamicbytes,arrays,structs) store a reference to data, allowing multiple variables to point to the same information. - You also learned how to declare and initialize variables, understanding their default values.
Next, we'll dive into how to control the flow of your smart contracts!
자주 묻는 질문
“Solidity 데이터 형식과 변수” 강의는 무료인가요?
네 — “Solidity 데이터 형식과 변수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.
“Solidity 데이터 형식과 변수”에서 뭘 배우나요?
Solidity의 값 형식과 참조 형식, 변수 선언 및 초기화 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Solidity 데이터 형식과 변수” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Solidity 데이터 형식과 변수
- 제어 구조와 반복문
- 함수와 가시성 지정자
- 구조체와 열거형