赞
踩
使用unstable feature的条件和步骤:
1. 只有nightly才可以使用unstable
2. 找到unstable feature的名字
3. #![feature(xxx)]启用这个feature
下面是 std::ptr里的as_ref引起的 编译器错误来举例:
use of unstable library feature ‘ptr_as_ref’: Option is not clearly the right return type, and we may want to tie the return lifetime to a borrow of the raw pointer (see issue #27780)
可以看到编译器给出了很多提示告诉你这是个unstable的,并且给出了原因。我们先找到这个:feature 'ptr_as_ref'
,那么ptr_as_ref就是这个feature的名字了。启用就是添加:#![feature(ptr_as_ref)]
注:括号里就是feature的名字了,这个替换成你需要的名字即可
如果想了解更多可以继续往下看:
上面那句警告其实是源代码里写的,原始的代码在这儿:
https://doc.rust-lang.org/src/core/ptr.rs.html#318
我把代码复制过来了:
#[unstable(feature = "ptr_as_ref",
reason = "Option is not clearly the right return type, and we \
may want to tie the return lifetime to a borrow of \
the raw pointer")]
#[inline]
pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
if self.is_null() {
None
} else {
Some(&**self)
}
}
从上面代码可以看到#[unstable(feature = "ptr_as_ref",reason = "...")]
feature = “ptr_as_ref” 就是这个feature的名字,reason就是编译器提示的内容了
下面是比较完整的列子:
#![feature(ptr_as_ref)]
use std::ptr;
struct Foo(i32);
impl Foo{
fn print(&self){
println!("{}",self.0);
}
fn set(&mut self,i:i32){
self.0 = i;
}
}
fn main(){
let mut f = Foo(100);
let pf = &mut f as *mut Foo;
let f2 = unsafe{pf.as_mut().unwrap()};
f2.set(2000);
f2.print();
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。