使用未声明的类型或模块 near_blockchain

Posted

技术标签:

【中文标题】使用未声明的类型或模块 near_blockchain【英文标题】:Use of undeclared type or module near_blockchain 【发布时间】:2021-01-14 11:23:13 【问题描述】:

尝试编译 NEAR 智能合约时出现以下错误,但仅在编译为 wasm 目标时出现

   Compiling nep9000 v0.1.0 (/Users/mikkoohtamaa/code/advanced-fungible-token/contract)
error[E0433]: failed to resolve: use of undeclared type or module `near_blockchain`
   --> src/token.rs:144:1
    |
144 | #[near_bindgen]
    | ^^^^^^^^^^^^^^^ use of undeclared type or module `near_blockchain```

正常的cargo build是可以的。

【问题讨论】:

【参考方案1】:

看来您需要在合同的structimpl 上声明#[near_bindgen],仅impl 是不够的。

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Token 
   ...



#[near_bindgen]
impl Token 

   ...


【讨论】:

虽然不知道为什么我只在 wasm 目标上收到此错误。【参考方案2】:

如果您在将 Rust 智能合约分解为单独的文件时遇到此错误,请使用 use crate::*; 而不是您的 IDE 可能建议的内容。

例如,假设我们的项目中有这样的文件结构:

.
├── Cargo.lock
├── Cargo.toml
├── src
│  ├── my_mod.rs.     ⟵ here is the module file
│  └── lib.rs
└── build-and-test.sh

当您添加像my_mod.rs 这样的新文件时,您需要确保lib.rs 具有:

mod my_mod;

my_mod.rs 内部,您的 IDE 可能会建议:

use crate::Contract;

应该替换为:

use crate::*;

【讨论】:

以上是关于使用未声明的类型或模块 near_blockchain的主要内容,如果未能解决你的问题,请参考以下文章

Swift 中的“使用未声明的类型”,即使类型是内部的,并且存在于同一个模块中

Rust Diesel 未构建错误使用未声明的板条箱或模块

类型命名空间未声明或不是简单类型

未声明的类型'有效',没有这样的模块'验证'

c语言定义一维数组,元素未初始化,那数组元素默认值是啥

Objective-C 库的 Swift “使用未声明的类型”