Last active
November 2, 2021 04:17
-
-
Save Shaun289/31e1a626e0bbb423ec9f361f471d56d5 to your computer and use it in GitHub Desktop.
Rust study : array and slices.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The rust by example ko https://hanbum.gitbooks.io/rustbyexample/content/primitives/array.html | |
compiled on https://play.rust-lang.org/ | |
result: | |
Standard Error | |
Compiling playground v0.0.1 (/playground) | |
Finished dev [unoptimized + debuginfo] target(s) in 1.09s | |
Running `target/debug/playground` | |
thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 5', src/main.rs:17:34 | |
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace | |
Standard Output | |
first element of the array: 1 | |
second element of the array: 2 | |
size of xs : 5 | |
array occupies 20 bytes | |
borrow the whole array as a slice | |
first element of the slice: 1 | |
the slice has 5 elements | |
borrow a section of the array as a slice | |
first element of the slice: 0 | |
the slice has 3 elements | |
*/ | |
use std::mem; | |
fn analyze_slice(slice: &[i32]) | |
{ | |
println!("first element of the slice: {}", slice[0]); | |
println!("the slice has {} elements", slice.len()); | |
} | |
fn panic_slice(slice: &[i32]) | |
{ | |
println!("panice slice! {}", slice[5]); | |
} | |
fn main() | |
{ | |
let xs: [i32; 5] = [ 1,2,3,4,5 ]; | |
let ys: [i32; 500] = [0; 500]; | |
println!("first element of the array: {}", xs[0]); | |
println!("second element of the array: {}", xs[1]); | |
println!("size of xs : {}", xs.len()); | |
// 배열은 스택에 할당된다. | |
println!("array occupies {} bytes", mem::size_of_val(&xs)); | |
println!("borrow the whole array as a slice"); | |
analyze_slice(&xs); | |
println!("borrow a section of the array as a slice"); | |
analyze_slice(&ys[1 .. 4]); | |
panic_slice(&xs[1 .. 5]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment