How to assign string to *mut () type?

pub struct TraitObject {
pub data: *mut (),


fn main() {

let mut a: String = "foo".to_string();
let b = TraitObject { data: &mut a };

//how to assign string to traitobject data field..
//then how to call trait object data field as string

What are you actually trying to do?

Am trying to understand internals trait object

Is this what you are trying to do?

pub struct TraitObject {
    pub ptr: *mut (),
    pub extra: usize,

fn main() {
    let a: String = "foo".to_string();
    let ref_a: &str = a.as_str();
    let b: TraitObject = unsafe { std::mem::transmute(ref_a) };
    println!("{:?}", b);

Is this transmute guaranteed to be safe, however? What about alignment, for example?

The transmute is undefined behavior because the layout of fat pointers is not defined. There are no alignment issues.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.