Why From is safe?

2026-11-03来源 Rust Users ForumEnglish

Hi!

I was using libc FFI crate, I'm transforming i32 -> OwnedFd -> TcpListener and instead of writing from_raw_fd(&fd) I've accidentally used from(fd): (something like this)

let socket: OwnedFd = socket(/* ... */); let listener = unsafe { std::net::TcpListener::from(socket) }; 

And I've got unused_unsafe. Looking at the documentation it's Just From<T> implementation.

Why it is implemented? We don't know whether it actually refers to a socket, whether it's a TCP socket, or whether it has been configured correctly for use as a TcpListener.

My question is more about the API design: why From<OwnedFd> is implemented at all? API suggests that conversion is safe for any OwnedFd, even though an arbitrary OwnedFd might not represent a valid TCP listening socket. Seems easy to misuse.

1 post - 1 participant

Read full topic

原文:https://www.a8q9.cn/en/article/why-from-ownedfd-is-safe-d20157.html

相关文章