提示:本文的MOVE是基于APTOS公链特性的MOVE语言学习
文章目录
Lesson7-STRUCT(类似结构体)特性解读
核心概念
Struct结构体,用来存储具有结构化的数据。sturct可以相互嵌套,可存储地址下作为资源。
- 命名必须以大写字母开头
- 可以通过has关键词赋与能力
修饰符
- Copy-值能够被复制。
- Drop-值可以在作用域结束时删除。
- Key-值可以用作全局存储操作的key。
- Store-值可以被全局存储。
除struct类型外,其他的类型默认具备store,drop,copy的能力,sturct最终是存储在用户的地址上(或者被销毁),不存在aptos合约里,aptos合约是一个全纯的函数。
drop
值能够在使用结束后被销毁。
copy
值能够在使用结束后被复制。
key
值可以用作全局存储操作的key。
store
值可以被全局存储,通常配合ky使用。
通过运行以下代码可以更好理解以上概念
``
module 0x42::Demo{
use std::debug;
use std::signer;
struct Foo has drop{
u: u64,
b: bool
}
#[test]
fun test(){
let f = Foo{u: 42, b:true};
debug::print(&f.u);
debug::print(&f.b);
}
#[test]
fun test2(){
let f = Foo{u: 42,b: true};
let Foo{u,b} = &mut f;
*u = 43;
debug::print(&f.u);
debug::print(&f.b);
}
//copy
struct Cancopy has drop, copy{
x: u64,
y: u64
}
#[test]
fun test3(){
let c = Cancopy{x: 42, y: 43};
let c2 = copy c;
let Cancopy{x,y} = &mut c2;
*x = 44;
debug::print(&c.x);
debug::print(&c2.x);
}
//store
struct Key has key,drop{
s: Struct
}
struct Struct has store,drop{
x: u64
}
#[test]
fun test4(){
let s = Struct{x: 42};
let k = Key{s: s };
debug::print(&k.s.x);
}
}
Lesson8-函数控制流if while loop
module 0x42::Demo{
use std::debug;
#[test]
fun test_if(){
let x=5 ;
let x2 = 10;
if (x == 6){
debug::print(&x);
}else {
debug::print(&x2)
}
}
#[test]
fun test_while(){
let x =5 ;
while ( x > 0 ) {
x = x-1;
if (x == 3){
continue ;
};
debug::print(&x);
}
}
#[test]
fun test_loop(){
let x=5;
loop{
x = x-1;
if (x == 3 ){
continue;
};
if (x == 0){
break ;
};
debug::print(&x);
}
}
}
Lesson9-模块的特性
引用
可以通过以下三种方式导入模块,用来更好的进行管理。注意命名不能重复。一般是 库::模块::方法
作用域
可以再全局定义,也可以定义在函数内部,只在所在的作用域内有效。
Public(friend)
声明当前模块信任用模块,受信任模块可以调用当前模块中具有public(friend)的可见性函数
Public
声明当前模块对外可供其他接口调用的方法。
Entery
声明可被链下调用的模块方法。
ma.move
module MyPackage::ma{
friend MyPackage::mc;
public fun num():u64{
66
}
public(friend) fun num2():u64{
88
}
}
mb.move
module MyPackage::mb{
#[test]
fun test(){
use std::debug::print;
use MyPackage::ma::num;
let n = num();
print(&n);
}
// #[test]
// fun test2(){
// use std::debug::print;
// use MyPackage::ma::num2;
//
// let n =num2();
// print(&n);
// }
}
mc.move
module MyPackage::mc{
#[test_only]
use MyPackage::ma::num;
#[test]
fun test(){
use std::debug::print;
use MyPackage::ma::num;
let n = num();
print(&n);
}
#[test]
fun test2(){
use std::debug::print;
use MyPackage::ma::num2;
let n =num2();
print(&n);
}
}
;
use MyPackage::ma::num;
let n = num();
print(&n);
}
#[test]
fun test2(){
use std::debug::print;
use MyPackage::ma::num2;
let n =num2();
print(&n);
}
}