Rust 의 클로저는 주변 변수를 캡처하는 익명 함수다. 컴파일러는 클로저마다 캡처한 값을 필드로 가진 struct 에 가까운 익명 타입을 만든다. 본문이 캡처한 값을 읽기만 하면 공유 참조를, 바꾸면 가변 참조를, 소비하면 값 자체를 필드로 둔다. 본문이 그 값으로 하는 일에 따라 클로저가 Fn·FnMut·FnOnce 중 무엇을 구현하는지도 정해진다. iterator 어댑터 map·filter 는 이런 클로저를 받아 struct 로 감쌀 뿐이고, 실제 계산은 collect 같은 메서드가 next 를 부를 때 일어난다.
캡처 방식은 클로저 크기로, 지연 평가는 println! 이 찍히는 순서로 확인했다. 아래 예제는 모두 rustc 1.94.1, edition 2021 에서 컴파일하고 aarch64-apple-darwin(Apple Silicon macOS)에서 실행했다. 크기는 64비트 타깃 기준이다.
캡처 방식 — 공유 참조, 가변 참조, 값
클로저 넷을 만들고 size_of_val 로 크기를 쟀다.
use std::mem::size_of_val;
fn main() {
let name = String::from("wid");
let mut count = 0;
let nothing = || println!("hello");
let read = || println!("{name}");
let mut bump = || count += 1;
println!("nothing = {} bytes", size_of_val(¬hing));
println!("read = {} bytes", size_of_val(&read));
println!("bump = {} bytes", size_of_val(&bump));
nothing();
read();
bump();
bump();
println!("count = {count}");
let consume = || drop(name);
println!("consume = {} bytes", size_of_val(&consume));
consume();
}
nothing = 0 bytes
read = 8 bytes
bump = 8 bytes
hello
wid
count = 2
consume = 24 bytes
아무것도 캡처하지 않은 nothing 은 0바이트다. read 와 bump 는 포인터 하나 크기인 8바이트로, 각각 &String 과 &mut i32 를 담았다. consume 은 String 자체(포인터·길이·용량)를 담아 24바이트다. 본문의 drop(name) 이 소유권을 가져가야 하기 때문이다.
The Rust Reference 는 캡처 방식을 불변 참조(이 글의 공유 참조), 가변 참조, 이동 순으로 나열하고(사이에 고유 불변 참조라는 특수한 방식이 하나 더 있다), 본문에서 값을 쓰는 방식과 맞는 첫 방식을 고른다고 적는다. 필요한 만큼만 빌린다.
가변 참조로 캡처한 클로저가 마지막으로 쓰이기 전까지는 원래 변수를 읽을 수 없다. 참조와 borrow 글의 대여 규칙이 클로저 필드에도 적용된다.
fn main() {
let mut count = 0;
let mut bump = || count += 1;
println!("{count}");
bump();
}
error[E0502]: cannot borrow `count` as immutable because it is also borrowed as mutable
--> capture_err.rs:4:16
|
3 | let mut bump = || count += 1;
| -- ----- first borrow occurs due to use of `count` in closure
| |
| mutable borrow occurs here
4 | println!("{count}");
| ^^^^^ immutable borrow occurs here
5 | bump();
| ---- mutable borrow later used here
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
bump 가 &mut count 를 필드로 갖고 있고, 5행에서 다시 쓰이므로 4행의 공유 참조와 겹친다. bump() 호출을 println! 앞으로 옮기면 컴파일된다.
move — 본문과 관계없이 값으로
move 를 붙이면 본문이 읽기만 해도 캡처한 변수를 값으로 가져간다.
use std::mem::size_of_val;
fn main() {
let name = String::from("wid");
let id = 7;
let by_ref = || println!("{name} {id}");
println!("by_ref = {} bytes", size_of_val(&by_ref));
by_ref();
let by_move = move || println!("{name} {id}");
println!("by_move = {} bytes", size_of_val(&by_move));
by_move();
by_move();
println!("id = {id}");
}
by_ref = 16 bytes
wid 7
by_move = 32 bytes
wid 7
wid 7
id = 7
본문은 같은데 by_ref 는 참조 두 개로 16바이트, by_move 는 String 24바이트와 i32 4바이트에 정렬용 패딩이 붙어 32바이트다. 필드 순서는 측정하지 않았고, 그림의 배치는 크기만 맞춘 것이다. id 는 Copy 라 클로저에 복사본이 들어가고, main 에서도 계속 쓸 수 있다. String 인 name 은 이동했으므로 move 클로저를 만든 뒤에 쓰면 E0382 가 난다.
fn main() {
let name = String::from("wid");
let greet = move || println!("hi {name}");
greet();
println!("{name}");
}
error[E0382]: borrow of moved value: `name`
--> move_err.rs:5:16
|
2 | let name = String::from("wid");
| ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
3 | let greet = move || println!("hi {name}");
| ------- ---- variable moved due to use in closure
| |
| value moved into closure here
4 | greet();
5 | println!("{name}");
| ^^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value before moving it into the closure
|
3 ~ let value = name.clone();
4 ~ let greet = move || println!("hi {value}");
|
move 가 꼭 필요한 곳은 클로저가 캡처한 변수보다 오래 살아야 할 때다. 함수가 클로저를 반환하면 함수의 지역 변수는 반환 시점에 사라지므로, 참조로 캡처한 클로저는 돌려줄 수 없다.
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
|x| x + n
}
fn main() {
let add5 = make_adder(5);
println!("{}", add5(1));
}
error[E0373]: closure may outlive the current function, but it borrows `n`, which is owned by the current function
--> return_err.rs:2:5
|
2 | |x| x + n
| ^^^ - `n` is borrowed here
| |
| may outlive borrowed value `n`
|
note: closure is returned here
--> return_err.rs:2:5
|
2 | |x| x + n
| ^^^^^^^^^
help: to force the closure to take ownership of `n` (and any other referenced variables), use the `move` keyword
|
2 | move |x| x + n
| ++++
본문 x + n 은 n 을 읽기만 하므로 컴파일러는 &n 으로 캡처했다. 컴파일러 제안대로 move |x| x + n 으로 바꾸면 n 의 복사본이 클로저에 들어가고 6 이 출력된다. 스레드로 클로저를 넘길 때도 같은 이유로 move 를 쓰는데, 거기에 따르는 Send·'static 조건은 이 글에서 다루지 않는다.
Fn, FnMut, FnOnce — 캡처한 값으로 하는 일
클로저를 인자로 받는 함수는 세 trait 중 하나를 bound 로 건다. 차이는 호출할 때 클로저 자신을 어떻게 받는지다. Fn 은 &self, FnMut 는 &mut self, FnOnce 는 self 로 받는다. 그래서 FnOnce 로 부른 클로저는 그 호출로 소비된다.
어느 trait 를 구현할지는 본문이 정한다. Reference 의 Call traits 절에 따르면 모든 클로저는 FnOnce 를 구현하고, 캡처한 값을 밖으로 옮기지 않으면 FnMut 를, 바꾸지도 않으면 Fn 까지 구현한다. std 에서도 Fn 은 FnMut 를, FnMut 는 FnOnce 를 supertrait 로 선언한다. Fn 클로저는 FnMut·FnOnce bound 자리에도, FnMut 클로저는 FnOnce 자리에도 넘길 수 있다.
fn call_twice<F: Fn()>(f: F) {
f();
f();
}
fn call_twice_mut<F: FnMut()>(mut f: F) {
f();
f();
}
fn call_once<F: FnOnce()>(f: F) {
f();
}
fn main() {
let name = String::from("wid");
let mut count = 0;
call_twice(|| println!("read {name}"));
call_twice_mut(|| count += 1);
println!("count = {count}");
call_once(|| println!("read {name}"));
call_once(move || drop(name));
}
read wid
read wid
count = 2
read wid
읽기만 하는 클로저는 Fn 이라 call_once 에도 넘어간다. 반대 방향은 거부된다. 값을 바꾸는 FnMut 클로저를 Fn 자리에 넘긴 경우다.
fn call_twice<F: Fn()>(f: F) {
f();
f();
}
fn main() {
let mut count = 0;
call_twice(|| count += 1);
}
error[E0594]: cannot assign to `count`, as it is a captured variable in a `Fn` closure
--> fn_mut_err.rs:8:19
|
1 | fn call_twice<F: Fn()>(f: F) {
| - change this to accept `FnMut` instead of `Fn`
...
7 | let mut count = 0;
| --------- `count` declared here, outside the closure
8 | call_twice(|| count += 1);
| ---------- -- ^^^^^^^^^^ cannot assign
| | |
| | in this closure
| expects `Fn` instead of `FnMut`
값을 소비하는 클로저를 Fn 자리에 넘기면 E0507 이 난다.
fn call_twice<F: Fn()>(f: F) {
f();
f();
}
fn main() {
let name = String::from("wid");
call_twice(|| drop(name));
}
error[E0507]: cannot move out of `name`, a captured variable in an `Fn` closure
--> fn_err.rs:8:24
|
7 | let name = String::from("wid");
| ---- ------------------- move occurs because `name` has type `String`, which does not implement the `Copy` trait
| |
| captured outer variable
8 | call_twice(|| drop(name));
| -- ^^^^ `name` is moved here
| |
| captured by this `Fn` closure
|
help: `Fn` and `FnMut` closures require captured values to be able to be consumed multiple times, but `FnOnce` closures may consume them only once
--> fn_err.rs:1:18
|
1 | fn call_twice<F: Fn()>(f: F) {
| ^^^^
help: consider cloning the value if the performance cost is acceptable
|
8 | call_twice(|| drop(name.clone()));
| ++++++++
FnOnce 만 구현한 클로저는 bound 없이 직접 부를 때도 두 번째 호출이 거부된다. 첫 호출이 클로저 값 자체를 이동시키기 때문이다.
fn main() {
let name = String::from("wid");
let consume = || drop(name);
consume();
consume();
}
error[E0382]: use of moved value: `consume`
--> once_err.rs:5:5
|
4 | consume();
| --------- `consume` moved due to this call
|
note: closure cannot be invoked more than once because it moves the variable `name` out of its environment
--> once_err.rs:3:27
|
3 | let consume = || drop(name);
| ^^^^
note: this value implements `FnOnce`, which causes it to be moved when called
--> once_err.rs:4:5
|
4 | consume();
| ^^^^^^^
move 와 FnOnce 는 별개다. move 는 캡처하는 방식을, Fn 계열은 본문이 캡처한 값으로 하는 일을 정한다. Reference 도 move 클로저가 여전히 Fn 이나 FnMut 일 수 있다고 적는다. 일반 함수도 시그니처가 맞으면 Fn bound 에 넘길 수 있다.
fn call_twice<F: Fn()>(f: F) {
f();
f();
}
fn double(x: i32) -> i32 {
x * 2
}
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(x)
}
fn main() {
let name = String::from("wid");
call_twice(move || println!("moved {name}"));
let offset = 10;
println!("{}", apply(double, 1));
println!("{}", apply(|x| x + offset, 1));
}
moved wid
moved wid
2
11
name 을 값으로 가져간 move 클로저가 call_twice 에서 두 번 불렸다. 본문이 name 을 읽기만 하므로 Fn 이다. 함수가 클로저를 받을 때는 가장 넓은 FnOnce 부터 생각하고, 여러 번 불러야 하면 FnMut, 공유 참조로 불러야 하면 Fn 으로 좁히는 순서가 호출하는 쪽에 거는 제약을 최소로 둔다고 봤다. 제네릭 bound 와 impl Trait 자체는 trait·제네릭·dyn 글에서 다뤘다.
Iterator trait 와 next
iterator 는 Iterator trait 를 구현한 타입이다. 필수 메서드는 하나다.
fn next(&mut self) -> Option<Self::Item>;
next 는 원소가 남아 있으면 Some, 끝나면 None 을 돌려준다. &mut self 로 받는 이유는 부를 때마다 내부 위치가 바뀌기 때문이다. 직접 구현해 보면 for 가 결국 next 를 반복해서 부르는 구조라는 점이 드러난다.
struct Countdown {
remaining: u32,
}
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.remaining == 0 {
return None;
}
self.remaining -= 1;
Some(self.remaining + 1)
}
}
fn main() {
let mut countdown = Countdown { remaining: 2 };
println!("{:?}", countdown.next());
println!("{:?}", countdown.next());
println!("{:?}", countdown.next());
for n in (Countdown { remaining: 3 }) {
print!("{n} ");
}
println!();
}
Some(2)
Some(1)
None
3 2 1
next 하나만 구현했는데 for 로 돌릴 수 있다. map·filter·collect 같은 나머지 메서드는 Iterator trait 의 기본 메서드라 Countdown 에서도 그대로 쓸 수 있다.
iter, iter_mut, into_iter — 원소를 어떻게 꺼내는가
Vec 에서 iterator 를 얻는 메서드는 셋이고, 셋이 내는 Item 타입 이름을 type_name 으로 출력했다.
fn item_type<I: Iterator>(_: &I) -> &'static str {
std::any::type_name::<I::Item>()
}
fn main() {
let mut names = vec![String::from("a"), String::from("b")];
println!("iter -> {}", item_type(&names.iter()));
println!("iter_mut -> {}", item_type(&names.iter_mut()));
for name in names.iter_mut() {
name.push('!');
}
for name in names.iter() {
print!("{name} ");
}
println!();
let owned = names.into_iter();
println!("into_iter -> {}", item_type(&owned));
let joined: Vec<String> = owned.collect();
println!("{joined:?}");
}
iter -> &alloc::string::String
iter_mut -> &mut alloc::string::String
a! b!
into_iter -> alloc::string::String
["a!", "b!"]
iter 는 &String 을 꺼내 읽기만 하고, iter_mut 는 &mut String 을 꺼내 원소를 제자리에서 바꾼다. 두 경우 names 는 그대로 남는다. into_iter 는 self 를 받아 Vec 을 소비하고 String 값 자체를 꺼낸다. for 는 IntoIterator::into_iter 로 iterator 를 얻는데, for x in &names, for x in &mut names, for x in names 는 각각 iter·iter_mut·into_iter 와 같은 Item 을 내는 iterator 를 만든다. 마지막 형태는 names 를 이동시키므로 반복문 뒤에서 쓸 수 없다.
fn main() {
let names = vec![String::from("a"), String::from("b")];
for name in names {
println!("{name}");
}
println!("{}", names.len());
}
error[E0382]: borrow of moved value: `names`
--> into_iter_err.rs:6:20
|
2 | let names = vec![String::from("a"), String::from("b")];
| ----- move occurs because `names` has type `Vec<String>`, which does not implement the `Copy` trait
3 | for name in names {
| ----- `names` moved due to this implicit call to `.into_iter()`
...
6 | println!("{}", names.len());
| ^^^^^ value borrowed here after move
|
note: `into_iter` takes ownership of the receiver `self`, which moves `names`
--> …/library/core/src/iter/traits/collect.rs:310:18
|
310 | fn into_iter(self) -> Self::IntoIter;
| ^^^^
help: consider iterating over a slice of the `Vec<String>`'s content to avoid moving into the `for` loop
|
3 | for name in &names {
| +
표준 라이브러리 경로는 줄였다. 컴파일러가 for 가 숨겨서 부른 .into_iter() 를 짚고, &names 로 바꾸라고 제안한다.
어댑터는 지연 평가된다
map·filter·take 처럼 iterator 를 받아 iterator 를 돌려주는 메서드를 어댑터라고 한다. 어댑터는 호출 시점에 아무것도 계산하지 않는다. map 만 부르고 결과를 쓰지 않으면 클로저 안의 println! 은 한 번도 실행되지 않고 경고가 나온다.
fn main() {
let numbers = vec![1, 2, 3];
numbers.iter().map(|n| {
println!("map {n}");
n * 10
});
println!("done");
}
warning: unused `Map` that must be used
--> lazy_warn.rs:3:5
|
3 | / numbers.iter().map(|n| {
4 | | println!("map {n}");
5 | | n * 10
6 | | });
| |______^
|
= note: iterators are lazy and do nothing unless consumed
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
help: use `let _ = ...` to ignore the resulting value
|
3 | let _ = numbers.iter().map(|n| {
| +++++++
done
Map struct 에 붙은 #[must_use = "iterators are lazy and do nothing unless consumed"] 가 이 경고를 낸다. 실행 결과에는 done 만 찍혔다.
계산은 collect·sum·for 처럼 iterator 를 소비하는 쪽이 next 를 부를 때 일어난다. 맨 끝의 소비자가 바로 앞 어댑터의 next 를 부르고, 그 어댑터가 다시 앞의 next 를 부르는 식이다. std 의 sum 같은 메서드는 fold 로 구현해 next 를 직접 부르지 않기도 하지만, 원소가 하나씩 체인을 지나는 순서는 같다. 원소마다 어느 단계를 지나는지 보려고 map 과 filter 에 println! 을 넣었다.
fn main() {
let numbers = vec![1, 2, 3, 4];
let picked: Vec<i32> = numbers
.iter()
.map(|n| {
println!("map {n}");
n * 10
})
.filter(|n| {
println!("filter {n}");
n % 20 == 0
})
.take(1)
.collect();
println!("picked = {picked:?}");
}
map 1
filter 10
map 2
filter 20
picked = [20]
map 이 네 원소를 먼저 다 처리하고 filter 가 이어받는 순서가 아니다. 1 이 map 과 filter 를 지나 버려진 뒤에야 2 를 꺼냈다. 20 이 take(1) 을 채우자 take 는 다음 next 에서 앞 단계를 부르지 않고 바로 None 을 돌려줬다. 그래서 3 과 4 는 map 에 들어가지도 않았다. 중간 Vec 이 만들어지지 않고, 필요한 원소까지만 계산된다.
map 의 시그니처를 보면 어댑터가 클로저에 거는 bound 가 보인다.
fn map<B, F>(self, f: F) -> Map<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> B,
map 은 원소마다 클로저를 부르므로 FnOnce 로는 안 되고, 클로저가 상태를 바꿔도 되도록 Fn 대신 FnMut 를 요구한다. 그래서 캡처한 변수를 바꾸는 클로저도 넘길 수 있다.
fn main() {
let words = vec!["fig", "apple", "banana"];
let mut calls = 0;
let lengths: Vec<usize> = words
.iter()
.map(|w| {
calls += 1;
w.len()
})
.collect();
println!("{lengths:?}, calls = {calls}");
}
[3, 5, 6], calls = 3
어댑터 체인은 클로저를 가진 struct
어댑터가 계산을 미룰 수 있는 것은 앞 iterator 와 클로저를 필드로 갖고 있기 때문이다. 체인을 만든 뒤 크기와 타입 이름을 출력했다.
use std::mem::size_of_val;
fn main() {
let numbers = vec![1, 2, 3, 4];
let threshold = 15;
let iter = numbers.iter();
println!("iter = {} bytes", size_of_val(&iter));
let mapped = numbers.iter().map(|n| n * 10);
println!("map = {} bytes", size_of_val(&mapped));
let filtered = numbers.iter().map(|n| n * 10).filter(|n| *n > threshold);
println!("map + filter = {} bytes", size_of_val(&filtered));
println!("{}", std::any::type_name_of_val(&filtered));
let total: i32 = filtered.sum();
println!("sum = {total}");
}
iter = 16 bytes
map = 16 bytes
map + filter = 24 bytes
core::iter::adapters::filter::Filter<core::iter::adapters::map::Map<core::slice::iter::Iter<'_, i32>, adapter_size::main::{{closure}}>, adapter_size::main::{{closure}}>
sum = 90
타입 이름이 그림의 중첩 구조 그대로다. Filter<Map<Iter<i32>, 클로저>, 클로저> 다. slice::Iter 는 16바이트이고, 아무것도 캡처하지 않은 map 클로저는 0바이트라 Map 도 16바이트다. filter 클로저는 &threshold 를 캡처해 8바이트를 더한다. 첫 절에서 본 클로저 크기 계산이 어댑터 체인 크기에 그대로 나타난다.
각 클로저는 고유한 타입이라 Filter 와 Map 도 그 클로저 타입마다 monomorphization 으로 사본이 만들어진다. 호출할 클로저가 컴파일할 때 정해지므로 인라인도 가능하다. 이 글에서 생성된 코드나 실행 시간을 측정하지는 않았다.
collect — 결과 타입을 정해 줘야 한다
collect 는 iterator 를 소비해 컬렉션을 만든다. 무엇을 만들지는 반환 타입으로 정해지므로, 타입을 알려 주지 않으면 컴파일되지 않는다.
fn main() {
let numbers = vec![1, 2, 3];
let doubled = numbers.iter().map(|n| n * 2).collect();
println!("{doubled:?}");
}
error[E0283]: type annotations needed
--> collect_err.rs:3:9
|
3 | let doubled = numbers.iter().map(|n| n * 2).collect();
| ^^^^^^^ ------- type must be known at this point
|
= note: cannot satisfy `_: FromIterator<i32>`
note: required by a bound in `collect`
--> …/library/core/src/iter/traits/iterator.rs:2022:19
|
2022 | fn collect<B: FromIterator<Self::Item>>(self) -> B
| ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Iterator::collect`
help: consider giving `doubled` an explicit type
|
3 | let doubled: Vec<_> = numbers.iter().map(|n| n * 2).collect();
| ++++++++
collect 의 반환 타입 B 는 FromIterator<Self::Item> 을 구현한 타입이면 된다. 원소 타입은 _ 로 두고 컬렉션 종류만 적어도 된다. 같은 collect 가 Vec, HashMap, String 을 모두 만든다.
use std::collections::HashMap;
fn main() {
let words = vec!["fig", "apple", "banana"];
let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect();
let by_len: HashMap<usize, &str> = words.iter().map(|w| (w.len(), *w)).collect();
let initials: String = words.iter().map(|w| w.chars().next().unwrap()).collect();
println!("{lengths:?}");
println!("{:?}", by_len.get(&5));
println!("{initials}");
}
[3, 5, 6]
Some("apple")
fab
(키, 값) 튜플을 내는 iterator 는 HashMap 으로, char 를 내는 iterator 는 String 으로 모인다. 어느 쪽이든 체인의 원소를 실제로 꺼내는 것은 이 collect 호출이다.
마무리
클로저는 캡처한 값을 필드로 가진 struct 였다. 본문이 읽기만 하는 read 는 8바이트 참조를, String 을 소비하는 consume 은 24바이트 String 을 담았다. move 는 이 캡처 방식만 값으로 바꾸고, 본문이 읽기만 하면 그 클로저는 여전히 Fn 이었다. Fn·FnMut·FnOnce 는 본문이 캡처한 값을 읽는지, 바꾸는지, 소비하는지로 정해진다.
iterator 쪽도 같은 구조였다. map·filter 는 앞 iterator 와 클로저를 필드로 가진 struct 를 하나 더 쌓을 뿐이고, collect 가 next 를 부를 때 원소 하나씩 체인을 지났다. take(1) 이 채워지자 3 과 4 는 꺼내지도 않았다. 클로저가 무엇을 담는지와 어댑터가 언제 그 클로저를 부르는지를 알면, 체인 한 줄이 무슨 일을 하는지 읽힌다고 봤다.
참고
- Rust 스마트 포인터:
Box·Rc·RefCell·Arc·Mutex, 스레드로 넘기는 클로저의Send - Rust trait, 제네릭, dyn: trait bound,
impl Trait, monomorphization - Rust 참조와 borrow: 공유 참조와 가변 참조가 겹칠 수 없는 대여 규칙
- Rust move, Copy, Clone: 값의 이동과
Copy타입의 복사 - The Rust Reference — Closure types
- The Rust Programming Language — Closures
- The Rust Programming Language — Processing a Series of Items with Iterators
std::ops::Fnstd::iter::Iterator