You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Move语言测试publish_balance泛型函数时遇类型推断失败报错

解决Move测试中“Could not infer this type”错误

问题根源

你编写的publish_balance是泛型函数(带有<CoinType>类型参数),但测试用例调用该函数时,编译器无法自动推断出CoinType的具体类型,因此抛出类型推断失败的错误。

原泛型函数代码

public fun publish_balance<CoinType>(account: &signer) {
    let empty_coin = Coin<CoinType> { value: 0 };
    assert!(!exists<Balance<CoinType>>(signer::address_of(account)), EALREADY_HAS_BALANCE);
    move_to(account, Balance<CoinType> { coin: empty_coin });
}

spec publish_balance {
    include Schema_publish<CoinType> {addr: signer::address_of(account), amount: 0};
}

spec schema Schema_publish<CoinType> {
    addr: address;
    amount: u64;

    aborts_if exists<Balance<CoinType>>(addr);

    ensures exists<Balance<CoinType>>(addr);
    let post balance_post = global<Balance<CoinType>>(addr).coin.value;

    ensures balance_post == amount;
}

报错的测试代码

#[test(account = @0xCAFE)]
fun test_publish_balance(account: signer) acquires Balance {
    publish_balance(&account);
    let addr = signer::address_of(&account);
    assert!(balance_of(addr) == 0, 0);
}

解决方法

调用泛型函数时显式指定具体的类型参数,明确告诉编译器CoinType对应的实际类型(比如你代码中定义的BasicCoin):

修改后的测试代码:

#[test(account = @0xCAFE)]
fun test_publish_balance(account: signer) acquires Balance {
    // 显式指定CoinType为你实际使用的Coin类型(示例为BasicCoin)
    publish_balance<BasicCoin>(&account);
    let addr = signer::address_of(&account);
    // 如果balance_of也是泛型函数,同样需要指定类型参数
    assert!(balance_of<BasicCoin>(addr) == 0, 0);
}

关键提示

  • Move编译器无法从上下文自动推断泛型参数时,必须手动添加类型注解
  • 将代码中的BasicCoin替换为你项目中实际定义的CoinType具体类型即可

内容的提问来源于stack exchange,提问作者MikhilMC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:40:13