Private method only for tests

I created a struct with some associated functions. One of those functions is a private function that is only used by tests, because I don't want to expose a private variable but I want to check its content in tests.

When I run cargo test or cargo build I get a dead code warning, but it works.

I have some questions though...

  1. Am I following a bad practice?
  2. Is this dead code compiled into my binary when I run cargo build?
  3. Is there a way to tell cargo to ignore that function when I run cargo build? I tried to add #[test] before the function, but an error message tells me that it is not allowed with associated functions.
  1. Not necessarily
  2. Probably, but it might get removed by later optimizations/at link time
  3. Use #[cfg(test)] to conditionally compile it when the whole thing is compiled for test mode.
2 Likes

2: Amazing. Where can I read more about rustc optimisations?
3: #[cfg(test)] did the trick. Thanks!

Note that unit tests within a module (including its submodules) can access that module's private fields and variables, as well its private functions. So you shouldn't need to add a private function just for accessing a private variable.

1 Like

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.