Rust- 结构体

2023-11-09

In Rust, a struct (short for “structure”) is a custom data type that lets you name and package together multiple related values that make up a meaningful group. If you’re coming from an object-oriented language, a struct is like an object’s data attributes.

Here’s an example of a struct in Rust:

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

// You can create an instance of the struct like this:
let user1 = User {
    email: String::from("someone@163.com"),
    username: String::from("someusername"),
    active: true,
    sign_in_count: 1,
};

This code defines a User struct that has four fields: username, email, sign_in_count, and active. The struct is then instantiated with the User { ... } syntax.

You can access the fields in a struct instance with dot notation:

println!("User's email: {}", user1.email);

Structs are also capable of having methods, which are defined within an impl block:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

let rect1 = Rectangle { width: 30, height: 50 };

println!(
    "The area of the rectangle is {} square pixels.",
    rect1.area()
);

In the above code, Rectangle is defined with width and height fields, and an area method is defined for it. The area method can be called on instances of Rectangle with dot notation, just like fields.

There are a few different types of structs in Rust, each with different use cases:

  • Classic structs, which are named and have a set of named fields. This is the most commonly used.

  • Tuple structs, which are named and have a set of unnamed fields. These are useful when you want to give a name to a tuple.

  • Unit structs, which are field-less, are useful for cases when you need to implement a trait on some type but don’t have any data you need to store in the type itself.

// Tuple struct
struct Color(u8, u8, u8);

let white = Color(255, 255, 255);

// Unit struct
struct Unit;

A comprehensive case is as follows:

fn main() {
    /*
       元组结构体
       struct Pair(String, i32);

       C语言风格结构体
       struct 结构体名称 {
           ...
       }

       单元结构体,不带字段,在泛型中很有用。
       type Unit


       struct 结构体名称 {
           字段1:数据类型
           字段2:数据类型
           ...
       }

       let 实例名称 = 结构体名称 {
           字段1:数据1
           字段2:数据2
           ...
       }
    */

    let s = Study {
        name: String::from("Rust"),
        target: String::from("可以熟练书写Rust程序"),
        spend: 36,
    };

    println!("{:?}", s);    // 输出:Study { name: "Rust", target: "可以熟练书写Rust程序", spend: 36 }
    println!("{}", s.name); // 输出:Rust

    let s3 = get_instance(
        String::from("Rust Programming Language"),
        String::from("熟练书写Rust程序"),
        36,
    );

    println!("{:?}", s3);   // 输出:Study { name: "Rust Programming Language", target: "熟练书写Rust程序", spend: 36 }
    // show(s3);

    /*
       impl 结构体 {
           fn 方法名(&self, 参数列表) 返回值 {
               // 方法体
           }
       }

       函数 可以直接调用,同一个程序不能出现2个相同的函数签名的函数,因为函数不归属任何owner.
       方法 归属某一个owner,不同的owner可以有相同的方法签名。

       &self 表示当前结构体的实例。也是结构体普通方法固定的第一个参数,其他参数可选。

       结构体静态方法
       fn 方法名(参数:数据类型,...) -> 返回类型 {
            // 方法体
       }
       调用方式  结构体名称::方法名(参数列表)
    */

    println!("spend {}", s3.get_spend());   // 输出:spend 36

    let s4 = Study::get_instance_another(
        String::from("Rust Programming Language"),
        String::from("熟练书写Rust程序"),
        36,
    );

    println!("s4 {:?}", s4);    // 输出:s4 Study { name: "Rust Programming Language", target: "熟练书写Rust程序", spend: 36 }

    /*
       单元结构体
       是一个类型,有且只有一个值()
    */

    // 元组结构体
    let pair = (String::from("Rust"), 1);
    println!("pair 包含{:?} and {:?}", pair.0, pair.1); // 输出:pair 包含"Rust" and 1

    // 解构元组结构体
    let (study, spend) = pair;
    println!("pair 包含{:?} and {:?}", study, spend);   // 输出:pair 包含"Rust" and 1
}

fn show(s: Study) {
    println!(
        "name is {} target is {} spend is {}",
        s.name, s.target, s.spend
    );
}

fn get_instance(name: String, target: String, spend: i32) -> Study {
    return Study {
        name,
        target,
        spend,
    };
}

#[derive(Debug)]
struct Study {
    name: String,
    target: String,
    spend: i32,
}

impl Study {
    fn get_spend(&self) -> i32 {
        return self.spend;
    }

    fn get_instance_another(name: String, target: String, spend: i32) -> Study {
        return Study {
            name,
            target,
            spend,
        };
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rust- 结构体 的相关文章

随机推荐

  • IntelliJ IDEA 使用教程

    一 设置入口 1 快捷键 Ctrl Alt S 2 File gt Settings 3 View gt appearance gt Toolbar 单击选中 出现工具栏图标 以后可直接点击它进入设置界面 之后的相关设置后 请点击Apply
  • 列车调度问题PTA

    7 20 列车调度 25 分 火车站的列车调度铁轨的结构如下图所示 两端分别是一条入口 Entrance 轨道和一条出口 Exit 轨道 它们之间有N条平行的轨道 每趟列车从入口可以选择任意一条轨道进入 最后从出口离开 在图中有9趟列车 在
  • Python 正则表达式(完整)-------附LeetCode真题详细解析

    正则表达式 又称规则表达式 Regular Expression 在代码中常简写为regex regexp或RE 是一种文本模式 包括普通字符 例如 a 到 z 之间的字母 和特殊字符 称为 元字符 是计算机科学的一个概念 正则表达式使用单
  • pread

    pread is a system call in Linux that allows reading data from a file descriptor at a specified offset without changing t
  • 面试经典(24)--二叉搜索树和双向链表

    题目描述 输入一棵二叉搜索树 将该二叉搜索树转换成一个排序的双向链表 算法分析 使用后续遍历方法 从10节点开始分析 只要左子树返回最大节点 右子树返回最小节点即可 正常递归无法判定当前是左子树还是右子树 所以参数要假如bool值判定左右子
  • Jmeter教程(二) - 自定义变量模拟多用户

    Jmeter教程 一 入门 Jmeter教程 二 自定义变量模拟多用户 Jmeter教程 三 Linux中使用命令行进行压测 在上一篇文章 Jmeter教程 一 入门 中介绍了Jmeter的基本用法 本文会继续介绍如何使用Jmeter对一个
  • 使用SpringSecurity,Jwt与Redis实现用户认证与授权

    spring security是spring官方比较推荐的用于认证和权限的解决方案 本次将围绕spring security的认证授权 jwt进行学习分享 1 依赖的引入
  • OpenMMLab AI实战营笔记-1

    OpenMMLab AI实战营笔记 1 第一课目录 OpenMMLab AI实战营笔记 1 OpenMMLab简介 安装教程 先安装Pytorch 安装mmcv 安装mmcv lite 安装完成 OpenMMLab简介 OpenMMLab是
  • Linux多线程编程三(互斥锁)

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 在线程实际运行过程中 我们经常需要多个线程保持同步 这时可以用互斥锁来完成任务 互斥锁的使用过程中 主要有pthread mutex init pthread mutex
  • mui.ajax php,求助!!!关于mui ajax获取不到后台数据

    js代码如下 mui ajax ajax php dataType json 服务器返回json格式数据 type post HTTP请求类型 headers Content Type application json success fu
  • 几种炫酷的加载动画

    动画一 An highlighted block
  • Typora常用快捷键

    Typora常用快捷键 Ctrl 1 一级标题 Ctrl 2 二级标题 Ctrl 3 三级标题 Ctrl 4 四级标题 Ctrl 5 五级标题 Ctrl 6 六级标题 Ctrl 0 段落 Ctrl 提升标题等级 Ctrl 降低标题等级 Ct
  • 什么是微服务?

    什么是微服务 微服务架构风格这种开发方法 是以开发一组小型服务的方式来开发一个独立的应用系统的 其中每个小型服务都运行在自己的进程中 并经常采用HTTP资源API这样轻量的机制来相互通信 这些服务围绕业务功能进行构建 并能通过全自动的部署机
  • 【点云处理技术之PCL】滤波器——直通滤波器(pcl::PassThrough)

    直通滤波器 是直接根据滤波器设定的条件 选择自己所需点云 可以选择保留设定范围内的点云 也可以选择滤除设定范围内的点云 保留或者滤出是由setFilterLimitsNegative进行模式开关的 代码中 设定z轴的条件 保留z方向范围 0
  • python pool.map 多线程 多参数

    python pool map 多线程 多参数 pool map默认只能传入一个参数 包上一个lambda分发参数 即可解决多参数传入问题 from multiprocessing import Pool from multiprocess
  • 数据挖掘中的数据清洗方法大全

    作者 章华燕 编辑 黄俊嘉 在数据挖掘领域 经常会遇到的情况是挖掘出来的特征数据存在各种异常情况 如数据缺失 数据值异常 等 对于这些情况 如果不加以处理 那么会直接影响到最终挖掘模型建立后的使用效果 甚至是使得最终的模型失效 任务失败 所
  • 将matlab变量导入excel并生成行列标题

    1 将matlab里生成的变量导入到excel中 xlswrite 具体路径 data xlsx AG set 1 B1 k1 xlswrite 表格路径 变量名称 sheet1 数据显示的范围 2 为生成的表格指定行列标题 xlswrit
  • React的事件处理

    目录 一 React的事件处理 1 与DOM事件处理的不同之处 1 React事件的命名方式 小驼峰方式 DOM的命名方式是小写 2 事件处理函数是以对象的方式赋值 而不是以字符串的方式赋值 3 阻止默认事件的方式不同 2 React中事件
  • /PROC/MEMINFO之谜

    proc meminfo是了解Linux系统内存使用状况的主要接口 我们最常用的 free vmstat 等命令就是通过它获取数据的 proc meminfo所包含的信息比 free 等命令要丰富得多 然而真正理解它并不容易 比如我们知道
  • Rust- 结构体

    In Rust a struct short for structure is a custom data type that lets you name and package together multiple related valu