11question : |-
22 ```rust
3- // This code simulates a library crate with pub(crate) visibility
4- // In a real scenario, main.rs would be in a separate crate
5-
3+ // mylib/src/lib.rs
64 mod mylib {
75 pub mod utils {
8- pub(crate) fn internal_helper () -> i32 { 42 }
9- pub fn public_helper () -> i32 { 24 }
6+ pub(crate) fn compute_offset () -> i32 { 42 }
7+ pub fn calculate_sum () -> i32 { 24 }
108 }
119 }
10+ ```
1211
12+ ```rust
13+ // main.rs (separate binary crate)
1314 fn main() {
1415 use mylib::utils;
15- println!("{}", utils::public_helper ());
16- println!("{}", utils::internal_helper ());
16+ println!("{}", utils::calculate_sum ());
17+ println!("{}", utils::compute_offset ());
1718 }
1819 ```
1920
@@ -23,24 +24,23 @@ answers:
2324- Only the first call works, second fails with "function is private"
2425- Only the second call works, first fails with "function is private"
2526- Both calls fail because the `utils` module is not accessible
26- correct_answer : 0
27+ correct_answer : 1
2728expected_output :
28- - ' 24'
29- - ' 42'
29+ - ' private function'
3030explanation : |-
3131 This question tests understanding of Rust's `pub(crate)` visibility modifier and
3232 crate boundaries. The `pub(crate)` modifier makes an item public within the
3333 defining crate but private across crate boundaries.
3434
35- In this code, both `internal_helper ()` (marked `pub(crate)`) and
36- `public_helper ()` (marked `pub`) are defined in the `mylib` module. Since
35+ In this code, both `compute_offset ()` (marked `pub(crate)`) and
36+ `calculate_sum ()` (marked `pub`) are defined in the `mylib` module. Since
3737 `main()` is in the same crate as the `mylib` module, both functions are
3838 accessible. The `pub(crate)` visibility allows access from anywhere within the
3939 same crate, so both function calls succeed and print "24" then "42".
4040
4141 The key distinction is that if `main.rs` were in a separate crate that depends
42- on `mylib` as an external library, then only `public_helper ()` would be
43- accessible. The `internal_helper ()` function would be private across the crate
42+ on `mylib` as an external library, then only `calculate_sum ()` would be
43+ accessible. The `compute_offset ()` function would be private across the crate
4444 boundary, resulting in a compilation error.
4545
4646 The key takeaway is that `pub(crate)` creates crate-local public visibility -
0 commit comments