# Why a Fn is required to be 'static when it is captured by another closure?

Considering following code

``````fn foo<F>(f:Box<F>)->Box<FnMut()->i32>
where F:Fn()->i32+'static   ///why F is required to be 'static? remove it and the compile will complain
{
let result=Box::new(move||{   //f is captured by move here
f()
});
result
}

fn bar()->Box<FnMut()->i32>{
foo(Box::new(||{1}))
}

fn main() {
let mut ff=bar();
println!("{}",ff())
}

``````

The generic parameter F is required to be 'static.

My questions are:

1. The input parameter `f` of function `foo` is boxed and captured by the inner closure `result` with the `move` keyword, why its type `F` (actually `Box<F>`) is required to be `'static`? It is passed by value and it is moved into the closure `result`, i.e., its ownership is transferred into the `result`, why its lifetime has to be `'static`?

2. In above code, the function `foo` is called in the function `bar`, then the input parameter of `foo` is apparently stack allocated, the lifetime of which is obviously not `'static`, but above program can be compiled and run, why? What does the `'static` mean in above program?

1 Like

The `Box<...>` result has an implicit bound of `'static`. You can add an arbitrary lifetime using

``````fn foo<'a, F>(f: Box<F>) -> Box<FnMut() -> i32 + 'a>
where F: Fn() -> i32 + 'a
{
Box::new(move || f())
}
``````
1 Like
{"ft_lang_label":"__label__en","ft_lang_prob":0.85020995,"math_prob":0.96779317,"size":1001,"snap":"2022-05-2022-21","text_gpt3_token_len":271,"char_repetition_ratio":0.10732196,"word_repetition_ratio":0.025974026,"special_character_ratio":0.2747253,"punctuation_ratio":0.13861386,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9549576,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-24T18:39:05Z\",\"WARC-Record-ID\":\"<urn:uuid:c6171a84-0f4c-4953-972b-207a340c285a>\",\"Content-Length\":\"20586\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:861410ee-59ea-416b-b2fb-01f5fa28976e>\",\"WARC-Concurrent-To\":\"<urn:uuid:84c73993-ae07-4fff-9ec6-e0d4a8befbe5>\",\"WARC-IP-Address\":\"64.71.144.205\",\"WARC-Target-URI\":\"https://users.rust-lang.org/t/why-a-fn-is-required-to-be-static-when-it-is-captured-by-another-closure/17005\",\"WARC-Payload-Digest\":\"sha1:HZKJCMAHYSSB2VOD2AAYF3AEP5ROXXTA\",\"WARC-Block-Digest\":\"sha1:ENOC6N6VFTHJMTTTOHYKCWLN5IZ3UTVO\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652662573189.78_warc_CC-MAIN-20220524173011-20220524203011-00049.warc.gz\"}"}