Rust分からない: 関数シグニチャー
main.rsはこうなってる:
code:src/main.rs
use epub_cache;
fn main() {
let epub_path = std::env::args().nth(1).expect("No EPUB file specified");
let cache_path = epub_cache::cache_path_from_path(&epub_path);
println!("{}", cache_path.to_string_lossy());
}
ここから参照してるlib.rsの書き方がよく分からない。
先にうまくいく例。
code:src/lib.rs
use std::path::{Path,PathBuf};
pub fn cache_path_from_path<P: AsRef<Path>>(path: P) -> PathBuf {
Path::new(".cache").join(path)
}
引数pathの型としてAsRef<Path>を指定している。
code:shell
% cargo clippy
うまくいかない例。
code:src/lib.rs
use std::path::{Path,PathBuf};
pub fn cache_path_from_path(path: &AsRef<Path>) -> PathBuf {
Path::new(".cache").join(path)
}
pathの型を境界の記法を使わないで書いた。
code:shell
% cargo clippy
Checking epub-cache v0.1.0 (/home/kitaitimakoto/src/gitlab.com/KitaitiMakoto/epub-cache)
warning: trait objects without an explicit dyn are deprecated
--> src/lib.rs:3:35
|
3 | pub fn cache_path_from_path(path: AsRef<Path>) -> PathBuf {
| ^^^^^^^^^^^ help: use dyn: dyn AsRef<Path>
|
= note: #[warn(bare_trait_objects)] on by default
errorE0277: the size for values of type (dyn std::convert::AsRef<std::path::Path> + 'static) cannot be known at compilation time --> src/lib.rs:3:29
|
3 | pub fn cache_path_from_path(path: AsRef<Path>) -> PathBuf {
| ^^^^ doesn't have a size known at compile-time
|
= help: the trait std::marker::Sized is not implemented for (dyn std::convert::AsRef<std::path::Path> + 'static)
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
errorE0277: the size for values of type dyn std::convert::AsRef<std::path::Path> cannot be known at compilation time --> src/lib.rs:4:30
|
4 | Path::new(".cache").join(path)
| ^^^^ doesn't have a size known at compile-time
|
= help: the trait std::marker::Sized is not implemented for dyn std::convert::AsRef<std::path::Path>
error: aborting due to 2 previous errors
For more information about this error, try rustc --explain E0277.
error: could not compile epub-cache.
To learn more, run the command again with --verbose.
この二つ、同等だと思ってたんだけどな……。
エラーメッセージは親切だし、直せるんだけど、自分の理解が間違ってるのが分からない。
環境は以下の通り。
code:shell
% cat /etc/os-release; rustc -V; cargo -V
NAME="Ubuntu"
VERSION="18.04.4 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.4 LTS"
VERSION_ID="18.04"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
rustc 1.41.0 (5e1a79984 2020-01-27)
cargo 1.41.0 (626f0f40e 2019-12-03)