I'm reading a Rust book and I am confused by this example:
use std::fmt::Display;
fn main() {
test("hello");
test2("hello")
}
fn test(s: &dyn Display) {
println!("{}", s);
}
fn test2(s: &str) {
println!("{}", s);
}
Passing &'static str
as a trait object fails:
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/main.rs:4:10
|
4 | test("hello");
| ^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `str`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= note: required for the cast to the object type `dyn std::fmt::Display`
Why does this fail and the second call work?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…