Skip to content

compilation failure of example code in 15.4.8 Scoping rules / Lifetimes / Static #1922

@cutelittlebox

Description

@cutelittlebox

the third code snippet on the Static chapter seems to be meant to run without errors as an example of valid code, but fails with 2 warnings and 1 error.

code snippet:

extern crate rand;
use rand::Fill;

fn random_vec() -> &'static [usize; 100] {
    let mut rng = rand::thread_rng();
    let mut boxed = Box::new([0; 100]);
    boxed.try_fill(&mut rng).unwrap();
    Box::leak(boxed)
}

fn main() {
    let first: &'static [usize; 100] = random_vec();
    let second: &'static [usize; 100] = random_vec();
    assert_ne!(first, second)
}

output from the run button:

Compiling playground v0.0.1 (/playground)
warning: unused import: `rand::Fill`
 --> src/main.rs:2:5
  |
2 | use rand::Fill;
  |     ^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: use of deprecated function `rand::thread_rng`: renamed to `rng`
 --> src/main.rs:5:25
  |
5 |     let mut rng = rand::thread_rng();
  |                         ^^^^^^^^^^
  |
  = note: `#[warn(deprecated)]` on by default

error[E0599]: no method named `try_fill` found for struct `Box<[{integer}; 100]>` in the current scope
 --> src/main.rs:7:11
  |
7 |     boxed.try_fill(&mut rng).unwrap();
  |           ^^^^^^^^
  |
help: there is a method `fill` with a similar name
  |
7 -     boxed.try_fill(&mut rng).unwrap();
7 +     boxed.fill(&mut rng).unwrap();
  |

For more information about this error, try `rustc --explain E0599`.
warning: `playground` (bin "playground") generated 2 warnings
error: could not compile `playground` (bin "playground") due to 1 previous error; 2 warnings emitted

modifying the snippet to this seems to work fine

extern crate rand;
use rand::Fill;

fn random_vec() -> &'static [u8; 100] {
    let mut rng = rand::rng();
    let mut boxed = Box::new([0; 100]);
    boxed.fill(&mut rng);
    Box::leak(boxed)
}

fn main() {
    let first: &'static [u8; 100] = random_vec();
    let second: &'static [u8; 100] = random_vec();
    assert_ne!(first, second)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions