Rust: Access the last value of a slice?

记录一下今后可能会踩的坑:

fn last<T: Clone>(slice: &[T]) -> T {
    slice[slice.len()-1].clone()
}

不加 .clone() 是不行的,因为 slice[slice.len()-1] 的值是属于 slice 的,不可移出。所以只能将其 copy 一份返回出来。我有预感以后一定会有忘记 .clone() 的时候……

 

Ref:

https://users.rust-lang.org/t/error-e0507-cannot-move-out-of-indexed-content/12815/2

Advertisements

Rust: Some important traits

std::fmt::Display

pub trait Display {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error>;
}

User-facing;

cannot be derived.

std::fmt::Debug

pub trait Debug {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error>;
}

Programmer-facing debug info;

can be used with #[derive] if all fields implement Debug

Debug: derived example from doc

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

println!("The origin is: {:?}", origin);

std::clone::Clone

Explicit duplication;

provide any type-specific behavior necessary to duplicate values safely.

pub trait Clone {
    fn clone(&self) -> Self;

    fn clone_from(&mut self, source: &Self) { ... }
}

std::marker::Copy

Implicit bit-wise duplication;

pub trait Copy: Clone { }

A type can implement Copy if all of its components implement Copy

 

Rust: Closures

When to use

We want to be able to specify some code in one place in our program, but then only execute that code if we actually need the result in some other place in our program.

An example from TRPL

let expensive_closure = |num| { 
    println!("calculating slowly..."); 
    thread::sleep(Duration::from_secs(2)); 
    num 
};

Note

  • If we try to use a different type with the same closure, we will get an error.