when ODIN_OS == "windows" close_fn :: proc(h: rawptr) windows.CloseHandle(transmute(windows.HANDLE)h) else when ODIN_OS == "linux" || ODIN_OS == "darwin" close_fn :: proc(fd: rawptr) sys.linux.close(transmute(int)fd)
rqt-close is not a magic keyword or a hidden runtime feature. It is a discipline . By writing an explicit close for every opened file, created handle, or allocated system object, you retain full control over your program’s interaction with the operating system.
h := CreateFile("data.txt", ...) defer CloseHandle(h) // Guaranteed to run on scope exit // ... use h ... odin rqt-close
If you have dependent resources (e.g., a file mapping before the file handle), close child resources first. 3. Defer is Your Friend Odin’s defer statement is perfect for pairing allocation with release:
close_resource :: proc(resource: ^Raw_Resource) when ODIN_OS == "windows" sys.windows.CloseHandle(resource.handle) else when ODIN_OS == "linux" sys.linux.close(resource.fd) resource.valid = false when ODIN_OS == "windows" close_fn :: proc(h: rawptr)
| Platform | Resource Type | Close Function | |----------|---------------|----------------| | Windows | HANDLE | CloseHandle | | Linux / macOS | file descriptor | close (syscall or libc) | | WebAssembly (WASI) | fd | fd_close |
In Odin, every open deserves a close, every create a destroy. Your future self (and your operating system) will thank you. h := CreateFile("data
Close_Handle :: proc(h: windows.HANDLE) -> bool if h == windows.INVALID_HANDLE_VALUE do return true return windows.CloseHandle(h)
if my_handle != INVALID_HANDLE CloseHandle(my_handle) my_handle = INVALID_HANDLE
Or for a cross-platform abstraction:
init_program :: proc() my_handle := CreateFile(...) runtime.add_cleanup(cleanup_my_resource, &my_handle)