클로저



클로저의 트레잇에 관하여 매우 혼동되는 부분이 있어, 스택오버플로 검색 결과 좋은 답변 발견. 그대로 옮겨 적어둔다.



주소: https://stackoverflow.com/questions/30177395/when-does-a-closure-implement-fn-fnmut-and-fnonce

원문:


The traits each represent more and more restrictive properties about closures/functions, indicated by the signatures of their call_... method, and particularly the type of self:

  • FnOnce (self) are functions that can be called once,
  • FnMut (&mut self) are functions that can be called if they have &mut access to their environment
  • Fn (&self) are functions that can still be called if they only have & access to their environment.

A closure |...| ... will automatically implement as many of those as it can.

  • All closures implement FnOnce: a closure that can't be called once doesn't deserve the name. Note that if a closure only implements FnOnce, it can be called only once.
  • Closures that don't move out of their captures implement FnMut, allowing them to be called more than once (if there is unaliased access to the function object).
  • Closures that don't need unique/mutable access to their captures implement Fn, allowing them to be called essentially everywhere.

These restrictions follow directly from the type of self and the "desugaring" of closures into structs (described in Finding Closure in Rust).



번역:

각 트레잇은 자신의 call_... 메서드 시그니처와 특정한 self 의 타입에 의해 나타나는, 클로저/함수의 제한적인 성질을 표현한다.

  • FnOnce (self) 는 한 번 호출 가능한 함수이다.

  • FnMut (&mut self) 는 스코프의 아이템에 &mut 으로 접근하는 함수이다. (스코프 변수에 값을 변경하는 동작이 있는 경우를 의미하는 듯)

  • Fn (&self) 는 스코프의 아이템에 오직 & 으로만 접근하는 함수이다. (스코프 변수에 값을 변경하는 동작이 없는 경우를 의미하는 듯)

클로저는 위 트레잇 중 가능한 많은 트레잇을 구현한다 (조건만 만족한다면 하나의 클로저가 다수의 트레잇의 구현체가 될 수 있음)
  • 모든 클로저는 FnOnce 를 구현한다: 한 번 호출할 수 없는 클로저는 이름을 가질 필요가 없다. 클로저가 오직 FnOnce 트레잇만을 구현한 경우, 이 클로저는 오직 한 번만 호출 가능하다.
  • 스코프의 아이템을 이동시키지 않는 클로저는 FnMut 를 구현한며, 한 번 이상 호출 가능하다. (함수 객체에 별칭이 아닌 접근 방법이 있는 경우)
  • 스코프의 아이템에 유니크/뮤터블 접근이 필요하지 않은 클로저는 Fn 을 구현하며, 기본적으로 어디서든 호출 가능하다.
이러한 제한 사항은 self 의 타입과 구조체에 대한 클로저의 'desugaring' 을 직접적으로 따른다.




'Rust' 카테고리의 다른 글

클로저(심화)  (0) 2018.03.07
라이프타임  (0) 2018.02.28
트레잇(Traits)  (0) 2018.02.28
제너릭 타입  (0) 2018.02.27
에러 핸들링(Result)  (0) 2018.02.26

+ Recent posts