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无法使用

相关推荐
NightCyberpunk7 分钟前
HTML、CSS
前端·css·html
xcLeigh18 分钟前
HTML5超酷响应式视频背景动画特效(六种风格,附源码)
前端·音视频·html5
zhenryx19 分钟前
前端-react(class组件和Hooks)
前端·react.js·前端框架
颜淡慕潇20 分钟前
【K8S系列】kubectl describe pod显示ImagePullBackOff,如何进一步排查?
后端·云原生·容器·kubernetes
ZwaterZ21 分钟前
el-table-column自动生成序号&&在序号前插入图标
前端·javascript·c#·vue
Clarify1 小时前
docker部署go游戏服务器(进阶版)
后端
IT书架1 小时前
golang面试题
开发语言·后端·golang
zhangjr05752 小时前
【HarmonyOS Next】鸿蒙实用装饰器一览(一)
前端·harmonyos·arkts
机器之心2 小时前
全球十亿级轨迹点驱动,首个轨迹基础大模型来了
人工智能·后端
不爱学习的YY酱2 小时前
【操作系统不挂科】<CPU调度(13)>选择题(带答案与解析)
java·linux·前端·算法·操作系统