Äú²éѯµÄ¹Ø¼ü´Ê½öÔÚÍøÒ³±êÌâ»òÖ¸Ïò´ËÍøÒ³µÄÁ´½ÓÖгöÏÖ¡£

(ÖÇËÑËÑË÷ºÍÍøÒ³ https://www.oschina.net/news/322560/rust-1-83-0-released µÄ×÷ÕßÎ޹أ¬²»¶ÔÆäÄÚÈݸºÔð¡£ÖÇËÑËÑË÷¿ìÕÕ½÷ÎªÍøÂç¹ÊÕÏʱ֮Ë÷Òý£¬²»´ú±í±»ËÑË÷ÍøÕ¾µÄ¼´Ê±Ò³Ãæ¡£)

UTF-8 Rust 1.83.0 ·¢²¼ - OSCHINA - ÖÐÎÄ¿ªÔ´¼¼Êõ½»Á÷ÉçÇø

Rust 1.83.0 ·¢²¼

À´Ô´: OSCHINA
2024-11-29 10:24:00

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

Õ¹¿ªÔĶÁÈ«ÎÄ
µã»÷ÒýÁì»°Ìâôã ·¢²¼²¢¼ÓÈëÌÖÂÛõ%
0 ÆÀÂÛ
1 ÊÕ²Ø
·ÖÏí
·µ»Ø¶¥²¿
¶¥²¿