一、提取函数消除重复
// 定义max函数
fn getMax(list: &[i32]) -> i32 {
let mut largest = list[0];
for &item in list { // 模式匹配 item就是i32类型了
if item > largest {
largest = item;
}
}
// 或者使用 *解引用也行 获取值
for item in list {
if *item > largest{
largest = *item;
}
}
return largest;
}
fn main() {
let old_list = vec![10,20,30,40,50];
let new_list = vec![60,70,80,90,100];
println!("max of old_list is {}",getMax(&old_list));
println!("max of new_list is {}",getMax(&new_list))
}
二、泛型
struct Point<T,U> {
x:T,
y:U,
}
fn main() {
let p1 = Point{x:5,y:10};
let p2 = Point{x:1.0,y:4.0};
}
struct Point<T> {
x:T,
y:T,
}
impl <T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
impl Point<i32> {
fn x1(&self) -> &i32 {
&self.x
}
}
fn main() {
let p = Point{x:5,y:10};
println!("p.x={}",p.x());
}
struct Point<T,U> {
x:T,
y:U,
}
impl<T,U> Point<T,U> {
fn mixup<V,W> (self,other:Point<V,W>) -> Point<T,W> {
Point {
x:self.x,
y:other.y,
}
}
}
fn main() {
let p1 = Point{x:5,y:4};
let p2 = Point{x:"hello",y:'c'};
let p3 = p1.mixup(p2);
println!("p3.x={} ,p3.y={}",p3.x,p3.y);
}
fn main() {
let integer = Some(5);
let float = Some(5.1);
}
三、Trait
// 定义trait
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline:String,
pub content:String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{} {} ", self.headline,self.content);
}
}
Trait作为参数
实现了两个trait Summary和Display
四、生命周期
fn main() {
{
let r;
{
let x = 5;
r = &x;
}
println!("r:{}",r); // x离开作用域 内存已经释放 报错
}
}
fn longest(x:&str,y:&str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(),string2);
println!("longest str is {}",result);
}
函数返回值包括一个借用值,但是签名没有说是从x还是y借用的
考虑引用一个named lifetime 命名生命周期参数解决
修改代码如下
// 两个引用的生命周期和泛型是一样的
fn longest<'a>(x:&'a str,y:&'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(),string2);
println!("longest str is {}",result);
}
修改代码如下
struct ImportantExcerpt<'a> {
part : &'a str,
}
fn main() {
let novel = String::from("some years ago...");
let first_sentence = novel.split('.')
.next()
.expect("cannot find");
let i = ImportantExcerpt {
part: first_sentence
};
}
struct ImportantExcerpt<'a> {
part : &'a str,
}
impl <'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
fn announce(&self,announcement:&str) -> &str {
println!("attention:{}",announcement);
self.part
}
}
fn main() {
let novel = String::from("some years ago...");
let first_sentence = novel.split('.')
.next()
.expect("cannot find");
let i = ImportantExcerpt {
part: first_sentence
};
}