I have some data I'd like to prevent from logging (PrivateData
), even on accident. But I'd still like to accept either those values or values with the Display
trait (mostly strings but also a few Enum
) in a function and struct. I tried implementing Into
for Display
and my PrivateDisplay
traits, but it's reporting that it doesn't have a size at compile time. Is there a way to work around that or another approach that could work for this use case? I'd like to avoid requiring the programmer to wrap the types manually (e.g., create_data(Value::PrivateDisplay(PrivateData(Box::new(String::new("test")))))
).
Code (playground)
use std::fmt;
use std::io::Read;
trait PrivateDisplay {
fn private_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result;
}
struct PrivateData(String);
impl PrivateDisplay for PrivateData {
fn private_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
enum Value {
Display(Box<dyn fmt::Display>),
PrivateDisplay(Box<dyn PrivateDisplay>),
}
impl Into<Value> for dyn fmt::Display {
fn into(self) -> Value {
Value::Display(Box::new(self))
}
}
impl Into<Value> for dyn PrivateDisplay {
fn into(self) -> Value {
Value::PrivateDisplay(Box::new(self))
}
}
struct Data {
value: Value,
}
fn create_data<V>(value: V) -> Data
where
V: Into<Value>
{
Data {
value: value,
}
}
fn main() {
create_data("test");
create_data(PrivateData(String::from("test")));
// May also be data provided from outside program
let mut buffer = String::from("buffer");
std::io::stdin().read_to_string(&mut buffer).unwrap();
create_data(buffer);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0277]: the size for values of type `(dyn std::fmt::Display + 'static)` cannot be known at compilation time
--> src/main.rs:20:6
|
21 | impl Into<Value> for dyn fmt::Display {
| ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn std::fmt::Display + 'static)`
error[E0277]: the size for values of type `(dyn PrivateDisplay + 'static)` cannot be known at compilation time
--> src/main.rs:26:6
|
27 | impl Into<Value> for dyn PrivateDisplay {
| ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn PrivateDisplay + 'static)`
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground`
To learn more, run the command again with --verbose.