2016-07-03 2 views
3

私はそうのような 、機能するようにディレクトリ名のリストを渡したい:関数へのパスのリストを渡すには?

use std::path::Path; 

fn test(dirs: &Vec<Path>) {} 

fn main() { 
    let dirs = vec![Path::new("/tmp"), Path::new("/var/tmp")]; 
    test(dirs); 
} 

しかし、それはコンパイルされません:

<anon>:3:5: 4:6 error: the trait bound `[u8]: std::marker::Sized` is not satisfied [E0277] 
<anon>:3  fn test(dirs: &Vec<Path>) { 
<anon>:4  } 
<anon>:3:5: 4:6 help: see the detailed explanation for E0277 
<anon>:3:5: 4:6 note: `[u8]` does not have a constant size known at compile-time 
<anon>:3:5: 4:6 note: required because it appears within the type `std::sys::os_str::Slice` 
<anon>:3:5: 4:6 note: required because it appears within the type `std::ffi::OsStr` 
<anon>:3:5: 4:6 note: required because it appears within the type `std::path::Path` 
<anon>:3:5: 4:6 note: required by `std::vec::Vec` 

はパスではありませんSizedように見えますか?

Vec<String>を機能させるにはどうすればいいですか? PathBuf?どのようにこれを錆びた方法で実装するのですか?

+0

https://doc.rust-lang.org/std/path/struct.PathBuf.html –

答えて

2

実際、Pathは、strとちょうど同じサイズのないタイプです。 Pathで作業する唯一の賢明な方法は、&Path(ちょうど&strのように)への参照です。だからあなたの例では、次のようになります。

use std::path::Path; 

fn test(dirs: &[&Path]) {} 

fn main() { 
    let dirs = vec![Path::new("/tmp"), Path::new("/var/tmp")]; 
    test(&dirs); 
} 

ない私も&[_]&Vec<_>を変更したこと。 Vecへの参照は、スライス(&[_])より強力ではないため、慣用的な方法は、参照の代わりにスライスをベクトルに渡すことです。


上記のソリューションは、あなたがtest機能に所有権を移転したくない場合は、正しい方法です。所有権(実際にパスデータを保存している文字列バッファを含む)を転送する場合は、PathBufを使用してください。

+0

実行時にリストがビルドされる動的な例を追加できますか? – Zelphir

+0

@Zelphirそれほど違いはありません。 ( 'test'の)関数宣言は、上記の私のコードとまったく同じです。単に 'dirs'ベクタを別の方法で埋めてください。しかし、これは本当にこの質問に関するものではありません...私はあなたの要求によって少し混乱しています、ごめんなさい。 –

関連する問題