슬라이스
빌린 뷰
슬라이스은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is a Slice?
A slice is a borrowed view into a contiguous part of a collection. It does not own data — it points into existing data.
Slices are written with a range inside brackets.
fn main() {
let arr = [1, 2, 3, 4, 5];
let part = &arr[1..4];
println!("{:?}", part);
}Slice Range Syntax
Ranges select a start and end index. The end is exclusive.
&v[1..4]— indices 1, 2, 3.&v[..3]— from start to 3.&v[2..]— from 2 to the end.
fn main() {
let v = vec![10, 20, 30, 40];
println!("{:?}", &v[..2]);
println!("{:?}", &v[2..]);
}String Slices
A string slice &str is a view into part of a String. Index ranges are by byte position.
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{} {}", hello, world);
}Whole-Collection Slices
Use &v[..] to slice the entire collection. This is how a Vec borrows as a slice.
fn main() {
let v = vec![1, 2, 3];
let whole = &v[..];
println!("{:?}", whole);
}Slices as Parameters
Functions that take &[T] accept both arrays and vectors. This makes them flexible.
fn sum(items: &[i32]) -> i32 {
let mut total = 0;
for x in items {
total += x;
}
total
}
fn main() {
let v = vec![1, 2, 3];
let a = [4, 5, 6];
println!("{} {}", sum(&v), sum(&a));
}Slices Borrow, Not Own
Because a slice borrows, the original collection must stay alive while the slice is used. The compiler enforces this.
fn main() {
let v = vec![100, 200, 300];
let s = &v[0..2];
println!("slice {:?}, original {:?}", s, v);
}Slice Length
Like other collections, slices have a len() method giving the number of elements they cover.
fn main() {
let v = vec![5, 6, 7, 8, 9];
let middle = &v[1..4];
println!("length {}", middle.len());
}first and last
Slices provide first() and last(), returning Options so empty slices are handled safely.
fn main() {
let data = [10, 20, 30];
let s = &data[..];
println!("{:?} {:?}", s.first(), s.last());
}Iterating a Slice
You can iterate over a slice just like any collection.
fn main() {
let v = vec![1, 2, 3, 4];
for x in &v[1..3] {
println!("{}", x);
}
}A First-Word Function
A common slice use case: returning a slice into existing text, like the first word of a sentence.
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b' ' {
return &s[0..i];
}
}
s
}
fn main() {
println!("{}", first_word("hello there"));
}Why Slices Are Safe
Slices avoid copying data while preventing dangling references. The borrow checker guarantees the underlying data outlives the slice.
fn main() {
let words = vec!["a", "b", "c", "d"];
let pair = &words[1..3];
println!("{:?}", pair);
}Quick Check
Recall what a slice represents.
Recap
Slices in Rust:
- A borrowed view:
&v[start..end], end exclusive. &stris a string slice;&[T]is an array/vector slice.- Slice parameters accept both arrays and vectors.
- The borrow checker keeps slices safe.
fn average(nums: &[i32]) -> i32 {
nums.iter().sum::<i32>() / nums.len() as i32
}
fn main() {
let v = vec![4, 8, 12];
println!("{}", average(&v[..]));
}자주 묻는 질문
“슬라이스” 강의는 무료인가요?
네 — “슬라이스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.
“슬라이스”에서 뭘 배우나요?
빌린 뷰 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“슬라이스” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.