Rust 1.83.0 Îȶ¨°æÒÑÕýʽ·¢²¼£¬Ö÷Òª´øÀ´ÒÔϱ仯£º
Ð嵀 const ¹¦ÄÜ
´Ë°æ±¾¶ÔÔÚ const contextsÖÐÔËÐеĴúÂëµÄ¹¦ÄܽøÐÐÁ˶àÏîÖØ´óÀ©Õ¹¡£Ö¸µÄÊDZàÒëÆ÷ÔÚ±àÒëʱ±ØÐëÆÀ¹ÀµÄËùÓдúÂ룺const
ºÍstatic
ÏîµÄ³õʼֵ¡¢Êý×鳤¶È¡¢Ã¶¾ÙÅбðÖµ¡¢const ·ºÐͲÎÊýÒÔ¼°¿É´Ó´ËÀàÉÏÏÂÎĵ÷Óõĺ¯Êý£¨const fn
£©¡£
¶Ô staticsµÄÒýÓᣵ½Ä¿Ç°ÎªÖ¹£¬³ýÁËstatic
ÏîµÄ³õʼ»¯±í´ïʽ֮Í⣬const contexts ¶¼½ûÖ¹ÒýÓÃstatic
Ïî¡£´ËÏÞÖÆÏÖÒÑÈ¡Ïû£º
static S: i32 = 25;
const C: &i32 = &S;
ÖµµÃ×¢ÒâµÄÊÇ£¬ÔÚ const contexts ÖÐÈÔÈ»²»ÔÊÐí¶ÁÈ¡¿É±ä»òÄÚ²¿¿É±ä¾²Ì¬µÄÖµ¡£´ËÍ⣬³£Á¿µÄ×îÖÕÖµ²»µÃÒýÓÃÈκοɱä»òÄÚ²¿¿É±ä¾²Ì¬£º
static mut S: i32 = 0;
const C1: i32 = unsafe { S };
// error: constant accesses mutable global memory
const C2: &i32 = unsafe { &S };
// error: encountered reference to mutable memory in `const`
ÕâЩÏÞÖÆÈ·±£ constants ÈÔÈ»ÊÇ¡°constant¡±£ºËüÃǵÄÇóÖµ¼°ÒÔ¼°ËüÃÇ×÷ΪģʽµÄº¬Ò壨¿ÉÄÜÉæ¼°È¡ÏûÒýÓÃÒýÓã©ÔÚÕû¸ö³ÌÐòÖ´Ðйý³ÌÖн«ÊÇÏàͬµÄ¡£
¾¡¹ÜÈç´Ë£¬»¹ÊÇÔÊÐí³£Á¿ÇóÖµµ½Ö¸Ïò¿É±ä¾²Ì¬»òÄÚ²¿¿É±ä¾²Ì¬µÄÔʼָÕ룺
static mut S: i32 = 64;
const C: *mut i32 = &raw mut S;
¿É±äÒýÓúÍÖ¸Õë¡£ÏÖÔÚ¿ÉÒÔÔÚ const contexts ÖÐʹÓÿɱäÒýÓãº
const fn inc(x: &mut i32) {
*x += 1;
}
const C: i32 = {
let mut c = 41;
inc(&mut c);
c
};
»¹Ö§³Ö¿É±äÔʼָÕëºÍÄÚ²¿¿É±äÐÔ£º
use std::cell::UnsafeCell;
const C: i32 = {
let c = UnsafeCell::new(41);
unsafe { *c.get() += 1 };
c.into_inner()
};
µ«ÊÇ£¬¿É±äÒýÓúÍÖ¸ÕëÖ»ÄÜÔÚ³£Á¿µÄ¼ÆËãÖÐʹÓã¬ËüÃDz»ÄܳÉΪ³£Á¿×îÖÕÖµµÄÒ»²¿·Ö£º
const C: &mut i32 = &mut 4;
// error[E0764]: mutable references are not allowed in the final value of constants
´Ë°æ±¾»¹¸½´øÁËÒ»ÕûÌ×й¦ÄÜ£¬ÕâЩº¯ÊýÏÖÔÚÔÚ const contextsÖкÜÎȶ¨¡£
ÏêÇé¿É²é¿´¹Ù·½¹«¸æ£ºhttps://blog.rust-lang.org/2024/11/28/Rust-1.83.0.html