[rust-dev] bikeshed on closure syntax

Patrick Walton pwalton at mozilla.com
Tue Apr 17 19:46:39 PDT 2012


Here's a little before-and-after with some of the syntax and semantic 
changes discussed (snippet from Sebastian Sylvan's raytracer [1] and 
modified slightly):

--- Before ---

     #[inline(always)]
     fn get_rand_env() -> rand_env {
         let rng = rand::rng();

         let disk_samples = vec::from_fn(513u) { |_x|
             // compute random position on light disk
             let r_sqrt = f32::sqrt(rng.next_float() as f32);
             let theta = rng.next_float() as f32 * 2f32 *
                         f32::consts::pi;
             (r_sqrt * theta.cos(), r_sqrt * theta.sin())
         }

         let mut hemicos_samples = [];
         for uint::range(0u, NUM_GI_SAMPLES_SQRT) { |x|
             for uint::range(0u, NUM_GI_SAMPLES_SQRT) { |y|
                 let (u, v) = ((x as f32 + rng.next_float() as f32) /
                               NUM_GI_SAMPLES_SQRT as f32,
                               (y as f32 + rng.next_float() as f32) /
                               NUM_GI_SAMPLES_SQRT as f32);
                 hemicos_samples.push(cosine_hemisphere_sample(u, v));
             }
         }

         {
             rng: rng,
             floats: vec::from_fn(513u,
                                  { |_x| rng.next_float() as f32 }),
             disk_samples: disk_samples,
             hemicos_samples: hemicos_samples
         }
     }

--- After ---

     #[inline(always)]
     fn get_rand_env() -> rand_env {
         let rng = rand::rng();

         let disk_samples = vec::from_fn(513): x {
             // compute random position on light disk
             let r_sqrt = rng.next_float().(f32).sqrt();
             let theta = rng.next_float().(f32) * 2.0 * f32::consts::pi;
             (r_sqrt * theta.cos(), r_sqrt * theta.sin());
         }

         let mut hemicos_samples = []/~;
         for uint::range(0, NUM_GI_SAMPLES_SQRT): x {
             for uint::range(0, NUM_GI_SAMPLES_SQRT): y {
                 let (u, v) = ((x.(f32) + rng.next_float().(f32)) /
                               NUM_GI_SAMPLES_SQRT.(f32),
                               (y.(f32) + rng.next_float().(f32)) /
                               NUM_GI_SAMPLES_SQRT.(f32));
                 hemicos_samples.push(cosine_hemisphere_sample(u, v));
             }
         }

         {
             rng: rng,
             floats: vec::from_fn(513, _ -> rng.next_float().(f32)),
             disk_samples: disk_samples,
             hemicos_samples: hemicos_samples
         };
     }

---

Patrick

[1]: https://github.com/brson/rustray/blob/master/raytracer.rs



More information about the Rust-dev mailing list