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

Rust wasm-pack编译警告E0446:公共接口含私有类型World

Rust WASM编译警告问题:private type World in public interface

问题代码

use wasm_bindgen::prelude::*;

#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
struct World {
    width: usize
}

#[wasm_bindgen]
impl World {
    pub fn new() -> World {
        World {
            width :8
        }
    }

    pub fn width(&self) -> usize {
            self.width
    }
}

编译警告信息

[INFO]: 🌀  Compiling to Wasm...
   Compiling snake_game v0.1.0 (C:\dev\my\rust\test\snake_game)
warning: private type `World` in public interface (error E0446)
  --> src\lib.rs:11:1
   |
11 | #[wasm_bindgen]
   | ^^^^^^^^^^^^^^^
   |
   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
   = note: `#[warn(private_in_public)]` on by default
   = note: this warning originates in the attribute macro `wasm_bindgen::prelude::__wasm_bindgen_class_marker` (in Nightly builds, run with -Z macro-backtrace for more info)

问题原因(大白话)

Rust里默认结构体是私有类型,只能在当前模块内部使用,但你通过#[wasm_bindgen]把World的构造方法new和width方法暴露给了外部(JS环境),这些公开方法的返回值用到了World类型——相当于把私有类型放到了公开接口里,逻辑上存在矛盾。Rust目前只是给出警告,未来会直接判定为错误。

解决办法

给World结构体加上pub关键字,让它变成公开类型,和你暴露的公开方法权限匹配:

#[wasm_bindgen]
pub struct World {
    width: usize
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:10:13