#[test] fun test_nodrop(){ let no_drop = NoDrop{ value :34}; print(&no_drop); letNoDrop{ value: _ } = no_drop; }
这个例子 NoDrop类型没有drop能力,对象离开作用域,需要析构,或者将对象的所有权转移.
第8行是析构对象的代码
2.3.4 不能析构时,能转移所有权:
{.line-numbers}
1 2 3 4 5 6 7 8 9 10 11
fun useNoDrop(o : NoDrop ) : NoDrop{ std::debug::print(&o); o }
#[test] fun testUseNoDrop(){ let o = NoDrop{value :4}; let d = useNoDrop(o); NoDrop{value:_} = d; }
第1行函数UseNoDrop获得了对象o
第3行,函数将N哦Drop对象o 返回出去,将所有权转移出去.
第10 行,显示代码析构这个NoDrop对象
2.3.5 独立存储在链上
对象独立存储在链上,必须具有key能力 has key
{.line-numbers}
1 2 3 4 5 6 7 8 9 10 11
public struct Keyable has key{ id : UID, }
#[test] fun test_key(){ let mut ctx = tx_context ::dummy(); let k = Keyable{ id: object::new(&mut ctx)}; std::debug::print(&k); transfer::transfer(k,ctx.sender()); }
use std::string::String; public struct Grandson has store{ name : String, } public struct Child has store{ name : String, child : Grandson, } public struct Parent has key{ id: UID, child: Child, } #[test] fun test_store_child(){ let mut ctx = tx_context::dummy(); let foo = Parent { id : object::new(&mut ctx), child: Child { name : b"one child".to_string(), child: Grandson{ name : b"a grandson".to_string(),
publicstructCoin has key,store{ id:UID, amount:u64 }
//借出钱 public fun borrow(amount:u64,ctx:&mut TxContext) :(Coin,Loan){ let feedback = amount * 103 /100; let c = Coin{ id: object::new(ctx),amount}; (c, Loan{feedback}) }