摘要: 方法语法 方法:完成特定功能的代码块(和函数是不同的结构,方法在结构体中定义) 方法与函数类似,使用 fn 关键字和名称声明,可以拥有参数和返回值,同时包含在某处调用该方法时会执行的代码 与函数不同之处 它们在结构体(或者枚举或 trait 对象)的上下文中被定义 第一个参数是 self,表示方法被 阅读全文
posted @ 2022-04-29 20:15 ragworm 阅读(104) 评论(0) 推荐(0)
摘要: 结构体例子 计算长方形面积 fn main() { let width1 = 30; let height1 = 50; println!( "The area of the rectangle is {} square pixels.", area(width1, height1) ); } fn 阅读全文
posted @ 2022-04-29 20:14 ragworm 阅读(50) 评论(0) 推荐(0)
摘要: 定义并实例化结构体(struct) 定义结构体 使用struct关键字给整个结构体命名 在大括号中定义每一部分的名字和类型,即字段(field) struct User { active: bool, username: String, email: String, sign_in_count: u 阅读全文
posted @ 2022-04-29 20:13 ragworm 阅读(524) 评论(0) 推荐(0)
摘要: 切片(slice) slice是一个没有所有权的数据类型 slice 允许引用集合中一段连续的元素序列,而不用引用整个集合 //该函数接收一个字符串,返回在字符串中找到第一个单词 //如果在字符串中没有找到空格,就返回整个字符串 fn first_word(s: &String) -> usize 阅读全文
posted @ 2022-04-29 20:12 ragworm 阅读(36) 评论(0) 推荐(0)
摘要: 引用与借用 引用是一种数据类型 & 符号就是引用 允许使用值但不获取其所有权 解引用(dereferencing) 解引用运算符 * fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); // &s1 阅读全文
posted @ 2022-04-29 20:11 ragworm 阅读(123) 评论(0) 推荐(0)
摘要: 所有权(ownership) 栈内存(Stack)与堆内存(Heap) 栈 按值的接收顺序来存储,按相反的谁徐将他们移除(后进先出)(last in, first out) 添加数据叫(压)入栈(pushing onto the stack) 移出数据叫(弹)出栈(popping off the s 阅读全文
posted @ 2022-04-29 20:10 ragworm 阅读(63) 评论(0) 推荐(0)
摘要: 控制流 if表达式 关键字if后跟条件 条件不加括号 if number < 5 { println!("condition was true"); } else { println!("condition was false"); } 条件必须是bool值(即结果必须为1或0,不可为其他整数等) 阅读全文
posted @ 2022-04-29 20:09 ragworm 阅读(43) 评论(0) 推荐(0)