OnceLock — 일회성 셀이 있는 동기화 타입

OnceLock — 일회성 셀이 있는 동기화 타입

OnceLock<T>는 한 번만 쓸 수 있는(cell) 동기화 타입이에요. 전역 정적 변수 등에서 지연 초기화를 스레드 안전하게 지원해요.

출처: Rust 공식 문서

본문

pub struct OnceLock<T> { /* private fields */ }

주요 메서드

pub const fn new() -> OnceLock<T>
pub fn get(&self) -> Option<&T>
pub fn get_mut(&mut self) -> Option<&mut T>
pub fn set(&self, value: T) -> Result<(), T>
pub fn get_or_init<F>(&self, f: F) -> &T where F: FnOnce() -> T
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result<T, E>
pub fn into_inner(self) -> Option<T>

예시

use std::sync::OnceLock;

static CELL: OnceLock<String> = OnceLock::new();
assert!(CELL.get().is_none());
let value = CELL.get_or_init(|| "hello".to_string());
assert_eq!(value, "hello");

최초 실행에서 get_or_init의 클로저가 한 번만 실행되고, 이후 접근은 초기화된 값을 반환해요.

더 알아보기 (Learn more)