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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s