Is it possible to make a private variable in Rust?

I am trying to generate prime numbers. The code must store all the generated primes (to generate the next one), have some private functions and one public function ( generate_next_prime ).

In Java or C ++, I would write the PrimesGen class, but in Rust there can be no private variables in the structure. In Python, I would probably write a PrimesGen module, but there cannot be variables in Rust modules.

This code compiles and runs:

 struct PrimesGen { primes_so_far: Vec<i32>, next_candidate: i32, } impl PrimesGen { pub fn new() -> PrimesGen { PrimesGen { primes_so_far: vec![], next_candidate: 2, } } } fn main() { let pg: PrimesGen = PrimesGen::new(); println!("{}", pg.next_candidate); } 

So what should I do?

+7
private rust
source share
1 answer

In Rust, a file is an implicit module. When you put some code in the foo.rs file, if you want to use this code, you must enter mod foo; , because the name of this file is implicitly the name of the module. The file with the main one is no exception: it is one module (basic module).

Now, inside the module, everything can have access to everything. Take a look at this small example to see:

 struct Foo { x: i32, // private } struct Bar {} impl Bar { fn foo(f: Foo) { let _ = fx; } } fn main() { let f = Foo { x: 42 }; Bar::foo(f); } 

Bar can access private members of Foo : in Rust, visibility works with a module, not a struct. Inside the same module you cannot do something personal for the same module.

So, if you want to make the variable private in your example, put your structure and implementation inside the module:

 mod prime { pub struct PrimesGen { primes_so_far: Vec<i32>, next_candidate: i32, } impl PrimesGen { pub fn new() -> PrimesGen { PrimesGen { primes_so_far: vec![], next_candidate: 2, } } } } fn main() { use prime::*; let pg: PrimesGen = PrimesGen::new(); println!("{}", pg.next_candidate); // error: field is private } 
+9
source share

All Articles