How to instantiate a public tuple struct(with private field) from a different module?

Viewed 3728

I have a module where a tuple struct is defined as:

#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd)]
pub struct Id(Vec<u8>);

I make use of this struct in another module which needs to be imported there. But when I try to instantiate this struct Id as:

let mut id = Id(newId.as_bytes().to_vec()); //newId is a String

it throws an error saying:

constructor is not visible here due to private fields

How do I make the unnamed field public (though I cannot in my case as this is part of an API)? Or is there a different way to initialize this struct ?

2 Answers

The field 0 is private, you can either make it public like this

pub struct Id(pub Vec<u8>);

or you add an explicit constructor like this

impl Id {
    pub fn new(param: Vec<u8>) -> Id {
        Id(param)
    }
}

and call it like

let mut id = Id::new("newId".as_bytes().to_vec());

If you don't want to make something public to worldwide, but want to make it visible within a certain module, you can use visibility qualifiers. Example:

pub struct Id(pub(crate) Vec<u8>);
Related