bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 33쪽 중 17쪽
) {
assert!(divide(10, 2) == 5, 0);
assert!(divide(7, 3) == 2, 0);
}
}
```
**Test function requirements:**
* Must have `#[test]` annotation
* Cannot take parameters (except with signer injection)
* Can have any visibility level
* Should use descriptive names starting with `test_`
### Test-Only Code
Use `#[test_only]` to include code exclusively for testing. This annotation excludes code from production bytecode:
```move
module 0x42::token {
struct Token has key {
balance: u64
}
public fun transfer(from: &signer, to: address, amount: u64) {
// Transfer implementation
}
#[test_only]
fun create_test_token(account: &signer, amount: u64) {
move_to(account, Token { balance: amount });
}
#[test_only]
use std::debug;
#[test(alice = @0x1)]
fun test_token_creation(alice: signer) {
create_test_token(&alice, 100);
assert!(exists<Token>(@0x1), 0);
}
}
```
**Test-only scope:**
* Functions, modules, structs, constants, and imports can be marked `#[test_only]`
* Only available in test builds
* Enables creating test utilities without bloating production code
### Expected Failures
Use `#[expected_failure]` to test error conditions:
```move
module 0x42::vault {
const EInsufficientBalance: u64 = 1;
public fun withdraw(amount: u64, balance: u64) {
assert!(balance >= amount, EInsufficientBalance);
}
#[test]
#[expected_failure(abort_code = EInsufficientBalance)]
fun test_insufficient_balance() {
withdraw(100, 50); // Should abort with EInsufficientBalance
}
#[test]
#[expected_failure] // Any failure is acceptable
fun test_division_by_zero() {
let _result = 10 / 0;
}
}
```
**Expected failure options:**
* `#[expected_failure]`: Test should abort with any error
* `#[expected_failure(abort_code = <code>)]`: Test should abort with specific code
* `#[expected_failure(arithmetic_error, location = Self)]`: Arithmetic errors
* `#[expected_failure(out_of_gas, location = Self)]`: Gas limit errors
## Signer Injection
Tests can receive signer parameters for testing account-specific functionality:
```move
module 0x42::account_manager {
struct Account has key {
balance: u64,
active: bool,
}
public fun create_account(owner: &signer, initial_balance: u64) {
move_to(owner, Account {
balance: initial_balance,
active: true,
});
}
#[test(user = @0x123)]
fun test_account_creation(user: signer) {
create_account(&user, 1000);
assert!(exists<Account>(@0x123), 0);
}
#[test(alice = @0x1, bob = @0x2)]
fun test_multiple_accounts(alice: signer, bob: signer) {
create_account(&alice, 500);
create_account(&bob, 750);
assert!(exists<Account>(@0x1), 0);
assert!(exists<Account>(@0x2), 0);
}
}
```
**Signer injection syntax:**
* `#[test(param_name = @address)]` for single signer
* `#[test(alice = @0x1, bob = @0x2)]` for multiple signers
* Parameter names must match function parameter names
* Only `signer` type parameters are supported
## Running Tests
```bash
# Run all tests in the package
movement move test
# Run tests matching a pattern
movement move test --filter "account"
```
**Test results:**
* **PASS**: Test completed successfully
* **FAIL**: Test failed with error details
* **TIMEOUT**: Test exceeded gas/instruction limits
## Best Practices
* Group related tests in the same module as the code being tested
* Use descriptive test names that explain what is being verified
* Test both success and failure cases with `#[expected_failure]`
* Keep tests lightweight for fast execution
## Summary
Move's unit testing framework provides comprehensive testing capabilities:
* **Test annotations**: `#[test]` for executable tests, `#[test_only]` for test helpers
* **Error testing**: `#[expected_failure]` with optional specific abort codes
* **Signer injection**: Automatic test account creation for testing functions requiring signers
* **Test organization**: Tests can be in dedicated modules or alongside source code
* **Bytecode exclusion**: Test code is excluded from production compilation
* **Detailed reporting**: Clear failure messages with abort codes and locations
* **CLI integration**: Run tests with `movement move test` command
# Uses and Aliases
URL: /devs/move-book/usesAndAliases
# Uses and Aliases
The `use` syntax creates aliases for modules and their members, making code more readable and reducing repetitive fully-qualified names. Aliases can be scoped to entire modules or specific expression blocks, providing flexible import management.
**Key benefits:**
* **Cleaner code**: Shorter, more readable function calls
* **Namespace management**: Avoid naming conflicts with local aliases
* **Selective imports**: Import only needed functions and types
* **Flexible scoping**: Module-level or block-level alias control
Uses and aliases are essential for organizing complex Move projects and creating maintainable code that clearly expresses dependencies and relationships between modules.
## Basic Module Aliases
### Simple Module Import
**Import patterns:**
* `use std::vector` - Import with original name
* `use std::option as opt` - Import with custom alias
* Aliases must follow Move naming conventions
Import entire modules with optional custom names:
```move
module 0x42::defi_app {
use std::vector;
use std::option as opt;
public fun create_portfolio(): vector<opt::Option<u64>> {
let mut portfolio = vector::empty();
vector::push_back(&mut portfolio, opt::some(100));
vector::push_back(&mut portfolio, opt::none());
portfolio
}
}
```
### Member-Specific Imports
**Member import syntax:**
* `use module::{member1, member2}` - Multiple members
* `use module::{member as alias}` - Member with custom name
* `use module::{Self, member}` - Module and member together
Import specific functions, structs, or constants:
```move
module 0x42::token_utils {
use std::vector::{push_back, pop_back, length};
use std::option::{Option, some, none};
public fun process_batch(items: &mut vector<u64>): Option<u64> {
if (length(items) > 0) {
some(pop_back(items))
} else {
none()
}
}
}
```
## Advanced Import Patterns
### Self References and Multiple Aliases
Combine module and member imports efficiently:
```move
module 0x42::math_utils {
use std::vector::{Self as vec, push_back, length as len};
public fun calculate_average(numbers: vector<u64>): u64 {
let total = 0;
let count = len(&numbers);
while (!vec::is_empty(&numbers)) {
total = total + vec::pop_back(&mut numbers);
}
total / count
}
}
```
**Self reference rules:**
* `Self` refers to the module itself
* Can be aliased like any other import
* Useful for mixing module and member access patterns
## Scoping Rules
### Module-Level Imports
Imports at module level are available throughout the entire module:
```move
module 0x42::storage_manager {
use std::vector;
use std::option::Option;
struct Storage has key {
data: vector<u64>
}
public fun store_data(account: &signer, values: vector<u64>) {
move_to(account, Storage { data: values });
}
public fun get_data(addr: address): Option<vector<u64>> {
if (exists<Storage>(addr)) {
std::option::some(borrow_global<Storage>(addr).data)
} else {
std::option::none()
}
}
}
```
### Block-Level Imports
Imports within expression blocks have limited scope:
```move
module 0x42::calculator {
public fun complex_calculation(x: u64, y: u64): u64 {
let result = {
use std::vector::{push_back, pop_back};
let mut temp = std::vector::empty();
push_back(&mut temp, x * 2);
push_back(&mut temp, y * 3);
pop_back(&mut temp) + pop_back(&mut temp)
};
// push_back not available here - would cause error
result
}
}
```
**Block scoping rules:**
* Imports must be first statements in blocks
* Aliases expire at block end
* Can shadow outer scope names
* Useful for temporary, localized imports
## Naming and Uniqueness Rules
### Naming Conventions
Aliases must follow standard Move naming rules:
```move
module 0x42::examples {
use std::vector::{
push_back as add_item, // Valid function alias
length as get_size, // Valid function alias
// push_back as AddItem, // ERROR: Functions use snake_case
};
use std::option::{
Option as Opt, // Valid struct alias
// Option as opt, // ERROR: Structs use PascalCase
};
}
```
### Uniqueness Requirements
Aliases within the same scope must be unique:
```move
module 0x42::conflict_examples {
// This would cause errors:
// use std::vector::push_back as add;
// use std::option::some as add; // Duplicate 'add'
// This is valid:
use std::vector::push_back as vec_add;
use std::option::some as opt_add;
public fun example() {
let mut v = std::vector::empty();
vec_add(&mut v, opt_add(42));
}
}
```
## Shadowing
Use aliases inside of an expression block can shadow names (module members or aliases) from the outer scope. As with shadowing of locals, the shadowing ends at the end of the expression block:
```move
module 0x42::math_library {
use std::vector;
public fun sum(numbers: vector<u64>): u64 {
vector::length(&numbers) // Uses std::vector::length
}
public fun process_data(): u64 {
let result = {
use std::vector::length as size;
// 'length' is shadowed by 'size' alias in this block
let data = vector::empty<u64>();
vector::push_back(&mut data, 10);
vector::push_back(&mut data, 20);
size(&data) // Returns 2
};
// 'length' shadow ends here
result + vector::length(&vector::singleton(5)) // Uses original std::vector::length
}
public fun nested_shadowing(): bool {
use std::vector::is_empty;
let outer_result = {
use std::vector::is_empty as empty_check;
// 'is_empty' is shadowed by 'empty_check'
let inner_result = {
use std::vector::length as is_empty;
// 'is_empty' is now shadowed by 'length' function!
let v = vector::singleton(42);
is_empty(&v) == 1 // Actually calls length, returns true
};
// 'is_empty' refers to 'empty_check' again
let v = vector::empty<u8>();
empty_check(&v) && inner_result
};
// 'is_empty' refers to original function again
outer_result && is_empty(&vector::empty<u64>())
}
}
```
**Key shadowing behaviors:**
* **Block scope**: Aliases only shadow names within their expression block
* **Nested shadowing**: Inner blocks can shadow aliases from outer blocks
* **Name restoration**: Original names become available again when the block ends
* **Any name can be shadowed**: Module members, previous aliases, or even unrelated functions
## Unused Use or Alias
An unused use will result in a warning when compiling:
```move
module 0x42::example {
use std::vector::{empty, push_back}; // WARNING!
// ^^^^^^^^^ Unused 'use' of alias 'push_back'. Consider removing it
fun example(): vector<u8> {
empty()
}
}
```
## Best Practices
* Place imports at the top of modules for clarity
* Use descriptive aliases that clarify intent
* Use module-level imports for frequent dependencies
* Keep import scopes as narrow as practical
## Summary
The `use` syntax provides flexible import management for Move code:
* **Module aliases**: Import entire modules with original or custom names
* **Member imports**: Import specific functions, structs, or constants
* **Flexible scoping**: Module-level or block-level alias control
* **Self references**: Combine module and member imports efficiently
* **Namespace management**: Avoid naming conflicts with local aliases
* **Cleaner code**: Shorter, more readable function calls
* **Naming conventions**: Aliases must follow Move naming rules
# Variables, Assignment and Scope
URL: /devs/move-book/variablesAssignmentAndScope
# Variables, Assignment and Scope
Variables in Move store data that your program can use and manipulate. This chapter covers how to declare variables, assign values to them, and understand their scope.
## Variable Declaration
Variables are declared using the `let` keyword:
```move
let x = 10;
let y = 20;
```
By default, variables are **mutable** - their value can be changed after being declared.
```move
let count = 0;
count = 5; // This is valid as variables are mutable by default
```
## Type Annotations
Move can usually infer the type of your variables, but you can explicitly specify types when needed:
```move
let age: u8 = 25;
let price: u64 = 1000;
let score: u32 = 0;
```
## Assignment and Mutation
Variables can be reassigned as they are mutable by default:
```move
let balance = 100;
balance = 150;
balance = balance + 50; // balance is now 200
```
## Variable Shadowing
You can declare a new variable with the same name as a previous variable. This is called **shadowing**:
```move
let x = 10;
let x = 20; // This shadows the previous x
let x = x + 5; // x is now 25
```
Shadowed variables can even have different types:
```move
let value = 42; // u64 (inferred)
let value = 100u8; // u8 (explicit)
```
## Variable Naming Rules
Variable names must follow these rules:
* Start with a letter (`a-z`) or underscore (`_`)
* Can contain letters, numbers, and underscores
* Cannot start with uppercase letters
```move
// Valid names
let age = 25;
let _temp = 10;
let user_count = 0;
let value2 = 100;
// Invalid names
// let Age = 25; // ERROR: starts with uppercase
// let 2value = 100; // ERROR: starts with number
```
## Delayed Assignment
You can declare a variable without immediately assigning a value, but you must assign it before use:
```move
let result;
if (condition) {
result = 10;
} else {
result = 20;
}
// result can now be used
```
## Using Variables Before Assignment
Move enforces that variables must be assigned a value before they can be used. This prevents common programming errors and ensures memory safety:
```move
let x;
// let y = x + 10; // ERROR: use of unassigned local `x`
x = 5;
let y = x + 10; // OK: x has been assigned
```
The Move compiler performs **definite assignment analysis** to ensure all code paths assign a value before use:
```move
let result;
if (some_condition) {
result = 100;
} else {
};
// ERROR: use of possibly unassigned local `result`
```
To fix this, ensure all code paths assign the variable:
```move
let result;
if (some_condition) {
result = 100;
} else {
result = 200;
};
// OK: result is assigned in all paths
```
### Partial Assignment in Complex Control Flow
The compiler tracks assignment across complex control structures:
```move
let value;
if (condition1) {
if (condition2) {
value = 10;
} else {
value = 20;
}
} else {
value = 30;
}
// OK: all paths assign value
```
## Scope
Variables are only accessible within the **scope** where they are declared. Scopes are defined by curly braces `{}`:
```move
let x = 10;
{
let y = 20;
let z = x + y; // x is accessible here
} // y and z are no longer accessible
// x is still accessible here
```
### Nested Scopes
Variables from outer scopes can be used in inner scopes:
```move
let outer = 100;
{
let inner = 50;
let sum = outer + inner; // Both variables accessible
{
let result = sum + outer; // All variables accessible
}
}
```
### Scope and Mutation
Variables can be mutated in any scope where they're accessible:
```move
let counter = 0;
{
counter = counter + 1; // Mutation survives the scope
}
// counter is now 1
```
## Multiple Variable Declaration
You can declare multiple variables at once using tuples:
```move
let (x, y) = (10, 20);
let (a, b, c) = (1, 2, 3);
```
This is useful for functions that return multiple values:
```move
fun get_coordinates(): (u64, u64) {
(100, 200)
}
let (x_pos, y_pos) = get_coordinates();
```
## Expression Blocks
Expression blocks are sequences of statements enclosed in curly braces. The value of the last expression becomes the block's value:
```move
let result = {
let a = 10;
let b = 20;
a + b // This value (30) is returned from the block
};
```
## Summary
Variables in Move provide a way to store and manipulate data in your programs. Key points to remember:
* Variables are **mutable by default**
* Variables have **scope** - they're only accessible within their declaration block
* **Shadowing** allows redeclaring variables with the same name
* **Type annotations** can be explicit or inferred by the compiler
* Variables must be **assigned before use**
Understanding these concepts will help you write clear and safe Move code. In the next chapters, we'll explore specific data types like integers, booleans, addresses, and vectors.
# Vector
URL: /devs/move-book/vector
# Vector Type
`vector<T>` is Move's built-in collection type for storing multiple values of the same type. Think of it as a dynamic array that can grow and shrink during program execution.
## What is a Vector?
A vector is a homogeneous collection that stores elements of the same type:
* **Dynamic size**: Can grow or shrink at runtime
* **Ordered**: Elements maintain their insertion order
* **Indexed**: Access elements by their position (0-based)
* **Homogeneous**: All elements must be the same type
## Creating Vectors
### Empty Vectors
```move
use std::vector;
let empty_numbers: vector<u64> = vector[];
let empty_addresses = vector<address>[];
let empty_with_function = vector::empty<u64>();
```
### Vectors with Initial Values
```move
let numbers = vector[1, 2, 3, 4, 5];
let addresses = vector[@0x1, @0x2, @0x3];
let single_item = vector[42u8];
```
### Type Inference
Move can often infer the vector type from context:
```move
let numbers = vector[10, 20, 30]; // Inferred as vector<u64>
let explicit: vector<u32> = vector[10, 20, 30]; // Explicit type
```
## Special Vector Types
### Byte Vectors (`vector<u8>`)
Byte vectors are commonly used for strings and binary data:
```move
// Byte strings (ASCII)
let message = b"Hello, Move!";
let empty_bytes = b"";
// Hex strings
let hex_data = x"48656C6C6F"; // "Hello" in hex
let hash = x"DEADBEEF";
```
## Common Vector Operations
### Adding Elements
```move
use std::vector;
let numbers = vector::empty<u64>();
vector::push_back(&mut numbers, 10);
vector::push_back(&mut numbers, 20);
vector::push_back(&mut numbers, 30);
// numbers is now [10, 20, 30]
```
### Accessing Elements
```move
let numbers = vector[10, 20, 30];
// Get element by index (returns reference)
let first = vector::borrow(&numbers, 0); // &10
let second = vector::borrow(&numbers, 1); // &20
// Check if vector contains an element
let has_twenty = vector::contains(&numbers, &20); // true
```
### Modifying Elements
```move
let numbers = vector[10, 20, 30];
// Modify element at index
let element_ref = vector::borrow_mut(&mut numbers, 1);
*element_ref = 25; // numbers is now [10, 25, 30]
// Remove and return last element
let last = vector::pop_back(&mut numbers); // 30
// numbers is now [10, 25]
```
### Vector Information
```move
let numbers = vector[10, 20, 30];
// Get vector length
let length = vector::length(&numbers); // 3
// Check if empty
let is_empty = vector::is_empty(&numbers); // false
// Find element index
let (found, index) = vector::index_of(&numbers, &20); // (true, 1)
```
## Advanced Operations
### Combining Vectors
```move
let first = vector[1, 2, 3];
let second = vector[4, 5, 6];
// Append second vector to first
vector::append(&mut first, second);
// first is now [1, 2, 3, 4, 5, 6]
```
### Removing Elements
```move
let numbers = vector[10, 20, 30, 40];
// Remove element at specific index
let removed = vector::remove(&mut numbers, 1); // 20
// numbers is now [10, 30, 40]
// Swap remove (faster but changes order)
let items = vector[1, 2, 3, 4];
let removed = vector::swap_remove(&mut items, 1); // 2
// items is now [1, 4, 3] (last element moved to removed position)
```
### Vector Utilities
```move
let numbers = vector[3, 1, 4, 1, 5];
// Reverse the vector
vector::reverse(&mut numbers);
// numbers is now [5, 1, 4, 1, 3]
// Swap elements
vector::swap(&mut numbers, 0, 4);
// numbers is now [3, 1, 4, 1, 5]
```
## Additional Methods
While the operations above are the most common, the `std::vector` module provides a few other useful functions.
### `singleton`
Creates a vector with a single element. This is a convenient shorthand for creating a ve프로젝트로 돌아가기