rust基础之结构体

        定义结构体,需要使用 struct 关键字并为整个结构体提供一个名字。结构体的名字需要描述它所组合的数据的意义。接着,在大括号中,定义每一部分数据的名字和类型,我们称为 字段field)。

1 定义

struct 类型名 {
    变量名 : 变量类型,
    ...
};
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

2 创建结构体

let mut user1 = User {
    active: true,
    username: String::from("someusername123"),
    email: String::from("someone@example.com"),
    sign_in_count: 1,
};
// 修改结构体字段
user1.email = String::from("anotheremail@example.com");
  • 提供方法

fn build_user(email: String, username: String) -> User {
    User {
        active: true,
        username: username,
        email: email,
        sign_in_count: 1,
    }
}
​
// 简易方法  因为 username 和 email 参数与结构体字段同名
fn build_user(email: String, username: String) -> User {
    User {
        active: true,
        username,
        email,
        sign_in_count: 1,
    }
}
  • 通过结构体更新语法从其他实例创建实例

let user2 = User {
    active: user1.active,
    username: user1.username,
    email: String::from("another@example.com"),
    sign_in_count: user1.sign_in_count,
};
// .. 语法指定了剩余未显式设置值的字段应有与给定实例对应字段相同的值。
let user2 = User {
    email: String::from("another@example.com"),
    ..user1
};
  • 使用没有命名字段的元组结构体来创建不同的类型

    也可以定义与元组(类似的结构体,称为 元组结构体tuple structs)。元组结构体有着结构体名称提供的含义,但没有具体的字段名,只有字段的类型。当你想给整个元组取一个名字,并使元组成为与其他元组不同的类型时,元组结构体是很有用的,这时像常规结构体那样为每个字段命名就显得多余和形式化了。

    要定义元组结构体,以 struct 关键字和结构体名开头并后跟元组中的类型。

struct Color(i32, i32, i32);
let color = Color(0, 1, 2);
  • 没有任何字段的类单元结构体

    定义一个没有任何字段的结构体!它们被称为 类单元结构体unit-like structs)因为它们类似于 (),即元组类型一节中提到的 unit 类型。类单元结构体常常在你想要在某个类型上实现 trait 但不需要在类型中存储数据的时候发挥作用。

    struct AlwaysEqual;
    let subject = AlwaysEqual;

结构体的方法和实现的trait

use core::cmp::Ordering;
​
# [derive(Debug, Eq, PartialEq, Ord)]
pub struct Matrix {
    pub col : u32,
    pub row : u32,
}
​
impl Matrix {
    pub fn area(&self) -> u64 {
        (self.col * self.row) as u64
    }
    pub fn print_matrix(&self) {
        println!("the matrix info col : {}, row : {}", self.col, self.row)
    }
​
    pub fn create_matrix(col : u32, row : u32) -> Matrix {
        Matrix {
            col,
            row,
        }
    }
    // other fucntions
}
impl PartialOrd for Matrix {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        // 先比较行在比较列
        if self.col == other.col {
            return Some(self.row.cmp(&other.row));
        }
        Some(self.col.cmp(&other.col))
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 C# 中调用 Rust 函数并返回结构体对象,可以使用 Rust 的 FFI(Foreign Function Interface)功能和 C# 的 Marshaling 功能来实现。 以下是一个基本的示例,假设 Rust 函数返回一个包含两个整数字段的结构体对象: 1. 在 Rust 中定义一个包含两个整数字段的结构体,并实现一个返回结构体对象的函数。 ```rust #[repr(C)] pub struct MyStruct { pub field1: i32, pub field2: i32, } #[no_mangle] pub extern "C" fn rust_function() -> MyStruct { MyStruct { field1: 1, field2: 2 } } ``` 2. 将 Rust 代码编译为动态链接库,使用命令行参数 --crate-type=cdylib。 ```bash $ rustc --crate-type=cdylib rust_lib.rs ``` 3. 在 C# 中使用外部函数声明 (DllImport) 和 C语言调用约定 (Calling Convention) 来声明 Rust 函数,并指定返回值类型为 IntPtr。 ```csharp using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct MyStruct { public int field1; public int field2; } class Program { [DllImport("rust_lib.dll", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr rust_function(); static void Main(string[] args) { // 调用 Rust 函数并获取返回值指针 IntPtr ptr = rust_function(); // 将返回值指针转换为结构体对象 MyStruct result = Marshal.PtrToStructure<MyStruct>(ptr); // 打印结构体字段值 Console.WriteLine("Field1: " + result.field1); Console.WriteLine("Field2: " + result.field2); } } ``` 在上面的示例中,我们将 Rust 中的结构体类型显式地指定为 C 语言的结构体布局(#[repr(C)]),并将 C# 中的结构体类型与之相对应([StructLayout(LayoutKind.Sequential)])。然后,在 C# 中使用 Marshal.PtrToStructure 将返回值指针转换为结构体对象,从而实现了 Rust 函数返回结构体对象在 C# 中的使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值