Trait std::os::fd::AsRawFd

1.0.0 · source ·
pub trait AsRawFd {
    fn as_raw_fd(&self) -> RawFd;
Expand description

A trait to extract the raw file descriptor from an underlying object.

This is only available on unix and WASI platforms and must be imported in order to call the method. Windows platforms have a corresponding AsRawHandle and AsRawSocket set of traits.

Required Methods§

Extracts the raw file descriptor.

This function is typically used to borrow an owned file descriptor. When used in this way, this method does not pass ownership of the raw file descriptor to the caller, and the file descriptor is only guaranteed to be valid while the original object has not yet been destroyed.

However, borrowing is not strictly required. See AsFd::as_fd for an API which strictly borrows a file descriptor.

use std::fs::File;
#[cfg(any(unix, target_os = "wasi"))]
use std::os::fd::{AsRawFd, RawFd};

let mut f = File::open("foo.txt")?;
// Note that `raw_fd` is only valid as long as `f` exists.
#[cfg(any(unix, target_os = "wasi"))]
let raw_fd: RawFd = f.as_raw_fd();


This impl allows implementing traits that require AsRawFd on Arc.

use std::net::UdpSocket;
use std::sync::Arc;
trait MyTrait: AsRawFd {
impl MyTrait for Arc<UdpSocket> {}
impl MyTrait for Box<UdpSocket> {}