Rust struct

Rust struct

  • 1.实例化需要初始化全部成员变量
  • 2.如果需要实例化对象可变,加上mut则所有成员变量均可变

Rust支持通过已实例化的对象,赋值给未赋值的对象的成员变量

rust 复制代码
#![allow(warnings)]
use std::io;
use std::error::Error;
use std::boxed::Box;
use std::convert::TryInto;
use std::cmp::Ordering;
use std::cmp::min;
use std::cmp::max;

struct User {
    name: String,
    age: i32
}

fn main() -> Result<(), Box<dyn Error>> {
    let u: User = User {
        name: String::from("sqs"),
        age: 12
    };
    print!("{} {} ", u.name, u.age);
    let b: User = User {
        name: String::from("sqssqs"),
        ..u
    };
    print!("{} {}", b.name, b.age);
    Ok(())
}

定义结构体中的方法

rust 复制代码
#![allow(warnings)]
use std::io;
use std::error::Error;
use std::boxed::Box;
use std::convert::TryInto;
use std::cmp::Ordering;
use std::cmp::min;
use std::cmp::max;

struct User {
    name: String,
    age: i32
}

impl User {
    fn print(&self) {
        println!("{} {}", self.name, self.age);
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let u: User = User {
        name: String::from("sqs"),
        age: 12
    };
    u.print();
    let b: User = User {
        name: String::from("sqssqs"),
        ..u
    };
    b.print();
    Ok(())
}

修改成员变量

rust 复制代码
#![allow(warnings)]
use std::io;
use std::error::Error;
use std::boxed::Box;
use std::convert::TryInto;
use std::cmp::Ordering;
use std::cmp::min;
use std::cmp::max;

struct User {
    name: String,
    age: i32
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut u: User = User {
        name: String::from("sqs"),
        age: 12
    };
    print!("{} {} ", u.name, u.age);
    u.name = String::from("sqssqs");
    u.age = 16;
    print!("{} {}", u.name, u.age);
    Ok(())
}

通过 借用 修改成员变量

rust 复制代码
#![allow(warnings)]
use std::io;
use std::error::Error;
use std::boxed::Box;
use std::convert::TryInto;
use std::cmp::Ordering;
use std::cmp::min;
use std::cmp::max;

struct User {
    name: String,
    age: i32
}

fn chageAge(u : &mut User){
    u.age = 10;
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut u: User = User {
        name: String::from("sqs"),
        age: 12
    };
    println!("{} {}", u.name, u.age);
    u.name = String::from("sqssqs");
    u.age = 16;
    println!("{} {}", u.name, u.age);
    chageAge(&mut u);
    println!("{} {}", u.name, u.age);
    Ok(())
}

通过 转移所有权 修改成员变量

rust 复制代码
#![allow(warnings)]
use std::io;
use std::error::Error;
use std::boxed::Box;
use std::convert::TryInto;
use std::cmp::Ordering;
use std::cmp::min;
use std::cmp::max;

struct User {
    name: String,
    age: i32
}

fn chageAge(mut u: User) -> User {
    u.age = 10;
    u
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut u: User = User {
        name: String::from("sqs"),
        age: 12
    };
    println!("{} {}", u.name, u.age);
    u.name = String::from("sqssqs");
    u.age = 16;
    println!("{} {}", u.name, u.age);
    u = chageAge(u);
    println!("{} {}", u.name, u.age);
    Ok(())
}

以下代码报错

rust 复制代码
#![allow(warnings)]
use std::io;
use std::error::Error;
use std::boxed::Box;
use std::convert::TryInto;
use std::cmp::Ordering;
use std::cmp::min;
use std::cmp::max;

struct User {
    name: String,
    age: i32
}

fn chageAge(mut u: User) -> User {
    u.age = 10;
    u
}

fn main() -> Result<(), Box<dyn Error>> {   
    let mut u: User = User {
        name: String::from("sqs"),
        age: 12
    };
    println!("{} {}", u.name, u.age);
    u.name = String::from("sqssqs");
    u.age = 16;
    println!("{} {}", u.name, u.age);
    let b: User = chageAge(u);
    println!("{} {}", u.name, u.age);
    Ok(())
}

报错详情

rust 复制代码
编译出错!
error[E0382]: borrow of moved value: `u.age`
  --> /main.rs:30:31
   |
21 |     let mut u: User = User {
   |         ----- move occurs because `u` has type `User`, which does not implement the `Copy` trait
...
29 |     let b: User = chageAge(u);
   |                            - value moved here
30 |     println!("{} {}", u.name, u.age);
   |                               ^^^^^ value borrowed here after move
   |
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.

原因

所有权已经从u给b导致u无法使用

相关推荐
高山我梦口香糖17 分钟前
[react]searchParams转普通对象
开发语言·前端·javascript
m0_7482352420 分钟前
前端实现获取后端返回的文件流并下载
前端·状态模式
m0_748240251 小时前
前端如何检测用户登录状态是否过期
前端
black^sugar1 小时前
纯前端实现更新检测
开发语言·前端·javascript
AskHarries2 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
寻找沙漠的人2 小时前
前端知识补充—CSS
前端·css
GISer_Jing2 小时前
2025前端面试热门题目——计算机网络篇
前端·计算机网络·面试
m0_748245522 小时前
吉利前端、AI面试
前端·面试·职场和发展
理想不理想v2 小时前
webpack最基础的配置
前端·webpack·node.js
pubuzhixing2 小时前
开源白板新方案:Plait 同时支持 Angular 和 React 啦!
前端·开源·github