Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

struct

rust

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 ?

like image 779
Rajeev Ranjan Avatar asked Sep 10 '18 10:09

Rajeev Ranjan


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());
like image 50
filmor Avatar answered Nov 12 '22 16:11

filmor


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>);
like image 21
Masaki Hara Avatar answered Nov 12 '22 17:11

Masaki Hara