UnsafeCell is a "magic" language-level struct. But the reason for the error isn't its magical properties, it's the fact that it is invariant in T instead of covariant. If you make your struct invariant in T (e.g. by using PhantomData), it will result in the borrow check error too.
"Invariant" here means that Item<&'long str> cannot coerce to Item<&'short str> for example.
Lifetime parameters on functions are always at least just-longer than the function body, so you can never borrow a local variable for as long as such a lifetime. That's what you're trying to do in the invariant case: borrow your str: String for 'a.
fn fun<'a>(item: Item<&'a str>) {
let str = "sg".to_string();
// Need to borrow for `'a`...
let str = str.as_str();
// ...so that you can pass a `T = &'a str` here
inner_fun(str, item);
}
It doesn't error in the covariant case because the Item<&'a str> can coerce to a Item<&'local str>, where 'local ends after the call to inner_fun.
You cannot emulate its effects using any struct not itself containing an UnsafeCell.
The way this is marked in the source code of the standard library is the attribute #[lang = "unsafe_cell"]. Any time you see #[lang], something special is going on.[1]
Though it might be as innocuous as the fact that for loops generate calls to the Iterator trait, so Iterator is a lang item. ↩︎