简体   繁体   中英

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

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 ?

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>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM