2017-05-31 48 views
2

當我嘗試使用每晚編譯器來編譯下面的代碼,我得到一個錯誤:的std :: PTR ::唯一還沒有命名的方法抵消

#![feature(alloc)] 
#![feature(unique)] 
#![feature(heap_api)] 
extern crate alloc; 

use std::ptr::{Unique, self}; 
use alloc::heap; 
use std::mem; 

fn main() { 
    unsafe { 
     let align = mem::align_of::<i32>(); 
     let elem_size = mem::size_of::<i32>(); 
     let ptr = heap::allocate(elem_size*5, align); 
     let a = Unique::new(ptr as *mut _); 
     println!("{}", *a.offset(2)); 
    } 
} 

錯誤:

rustc 1.19.0-nightly (5de00925b 2017-05-29) 
error: no method named `offset` found for type `std::ptr::Unique<_>` in the current scope 
    --> <anon>:16:27 
    | 
16 |   println!("{}", *a.offset(2)); 
    |       ^^^^^^ 

根據到docs,offset應該被定義爲Unique。我究竟做錯了什麼?

+2

看來文檔沒有更新。在最新的每晚'唯一'不實現'Deref '。你可以使用'* a.as_ptr()。offset(2)'代替。 '獨特'還不穩定,所以預計會有變化。 – red75prime

+1

最新的夜間文檔可​​以在https://doc.rust-lang.org/nightly/std/ptr/struct.Unique.html找到。 – kennytm

回答

4

與您正在使用的代碼相比,您正在閱讀過時的文檔。最新的夜間API可在https://doc.rust-lang.org/nightly/std/ptr/struct.Unique.html找到。

此前,Unique通過Deref特徵得到了.offset()方法到*mut T。在2017 May 6th因爲

Major difference is that I removed Deref impls, as apparently LLVM has trouble maintaining metadata with a &ptr -> &ptr API. This was cited as a blocker for ever stabilizing this API. It wasn't that ergonomic anyway.

如今得到*mut T,刪除了此Deref IMPL,你叫.as_ptr()。這是一個數值 - 而不是引用 - 引用函數,因此可以解決LLVM問題。

println!("{}", *a.as_ptr().offset(2)); 
//    ^~~~~~~~ 
相關問題