DFINITY - Motoko学习系列 Whoami example 源代码解析

源代码

import Principal "mo:base/Principal";

shared (install) actor class WhoAmI(someone : Principal) = 
  this { // Bind the optional `this` argument (any name will do)

  // Return the principal identifier of the wallet canister that installed this
  // canister.
  public query func installer() : async Principal {
    return install.caller;
  };

  // Return the principal identifier that was provided as an installation
  // argument to this canister.
  public query func argument() : async Principal {
    return someone;
  };

  // Return the principal identifier of the caller of this method.
  public shared (message) func whoami() : async Principal {
    return message.caller;
  };

  // Return the principal identifier of this canister.
  public func id() : async Principal {
    return await whoami();
  };

  // Return the principal identifier of this canister via the optional `this` binding.
  // This is much quicker than `id()` above, since it avoids the latency of `await whoami()`.
  public func idQuick() : async Principal {
    return Principal.fromActor(this);
  };
};

解析

shared (install) actor class WhoAmI(someone : Principal) = 
  this {//actor body}
install : 下载canister的用户Principal(负责人)
this : 将这个actor 绑定到 "this" 标识符

public shared (message) func whoami() : async Principal {
    return message.caller;
}
message是Principal类型, 具有caller属性。
可以用message.caller得出调用这个func的user/canister/func 的 id
注意,如果是func的await调用,那么就返回这个func的id,如果是canister就返回canister的id,用户等同理

public func id() : async Principal {
    return await whoami();
  };
await whoami : 即使是一个actor中的func相互调用,也要await,因此可以得出结论: 只要是func -> async 那么, 就要用await接收他的返回值 

public query func installer() : async Principal {
    return install.caller;
  };
install是下载者,返回下载者的Principal
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值