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

Rust中结构体是否需置于main外?结构体跨函数调用报错答疑

Fixing the "cannot find type User in this scope" Error & Your Struct Scope Question

Hey there! Let's break down your problem and clear up your confusion step by step.

First, the error you're hitting (error[E0412]: cannot find type User in this scope) comes down to Rust's scoping rules. You defined the User struct inside the main() function, which means it's only visible within main() itself. The build_user() function lives outside main(), so it can't see the struct definition at all—hence the "cannot find type" error.

Corrected Code

Here's how to fix your code by moving the User struct to a scope that both main() and build_user() can access:

// Define the User struct in the top-level scope (outside all functions)
struct User {
    name: String,
    email: String,
}

fn main() {
    let s1 = String::from("bob");
    let s2 = String::from("bob@aol.com");
    
    let user1 = build_user(s1, s2);
}

fn build_user(email: String, name: String) -> User {
    User { email, name }
}

Answering Your Question: Do I have to define the struct outside main()?

Put simply: Yes, if you need to use that struct in any function other than main(). You don't have to make it a strict "global" item (you could nest it in a module, for example), but it needs to live in a scope that's accessible to all functions that need to reference it.

If you only ever used User inside main(), defining it there would work perfectly fine. But since your build_user() function returns a User instance, that struct has to be visible to build_user() too. Moving it to the top level of your file is the standard, straightforward way to handle this in Rust.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:30:41