While experimenting, I managed to expose a private struct outside of its scope, you can't directly reference it, but the compiler doesn't seem to prevent you from using a value; you cannot, however, write the type.
Is this intended behavior?
#![feature(type_name_of_val)]
mod inner {
mod internal {
#[derive(Debug, Clone, PartialEq)]
pub struct MyInternalStruct {
pub field: usize,
}
}
use internal::*;
#[derive(Debug, Clone)]
pub struct MyPublicStruct {
pub internal: MyInternalStruct, // shouldn't this be a compile error, as it reveals a private struct in public context?
}
pub fn get_internal(n: usize) -> MyInternalStruct { // same with this
MyInternalStruct { field: n } // and this
}
}
use inner::*;
fn main() {
dbg!(get_internal(1)); // how are we able to get a value of a private type?
// get_internal(1) = MyInternalStruct { field: 1 }
let bound = get_internal(2); // we can bind this value
dbg!(&bound); // and use it
// &bound = MyInternalStruct { field: 2 }
let public = MyPublicStruct { internal: bound }; // and it is the same exact type
dbg!(std::any::type_name_of_val(&public)); // → std::any::type_name_of_val(&public) = "playground::inner::MyPublicStruct"
fn test<T>(what: T) -> T { // generics function as well
let huh = what;
huh
}
let why = get_internal(3);
let how = test(why.clone()); // methods work
assert_eq!(why, how); // succeeds
// Compile errors //
/*
let cannot_write_type: inner::MyInternalStruct = get_internal(3); // yet we cannot write it's type?
// error: struct import `MyInternalStruct` is private
let direct = inner::internal::MyInternalStruct { field: 4 }; // writing it directly doesn't work
// error: module `internal` is private
*/
}