What's the Rust way to modify a structure within nested loops?

后端 未结 3 988
后悔当初
后悔当初 2020-12-10 19:48

Given is an array of bodies that interact in some way with each other. As a newbie I approached it as I would do it in some other language:

struct Body {
            


        
3条回答
  •  猫巷女王i
    2020-12-10 20:14

    I know the question is like 2 years old, but I got curious about it.

    This C# program produces the original desired output:

    var bodies = new[] { new Body { X = 10, Y = 10, V = 0 },
                         new Body { X = 20, Y = 30, V = 0 } };
    
    for (int i = 0; i < 2; i++)
    {
        Console.WriteLine("Turn {0}", i);
    
        foreach (var bOuter in bodies)
        {
            Console.WriteLine("x:{0}, y:{1}, v:{2}", bOuter.X, bOuter.Y, bOuter.V);
            var a = bOuter.V;
            foreach (var bInner in bodies)
            {
                a = a + bOuter.X * bInner.X;
                Console.WriteLine("    x:{0}, y:{1}, v:{2}, a:{3}", bInner.X, bInner.Y, bInner.V, a);
            }
            bOuter.V = a;
        }
    }
    

    Since only v is ever changed, we could change the struct to something like this:

    struct Body {
        x: i16,
        y: i16,
        v: Cell,
    }
    

    Now I'm able to mutate v, and the program becomes:

    // keep it simple and loop only twice
    for i in 0..2 {
        println!("Turn {}", i);
        for b_outer in bodies.iter() {
    
            let mut a = b_outer.v.get();
    
            println!("x:{}, y:{}, v:{}", b_outer.x, b_outer.y, a);
            for b_inner in bodies.iter() {
    
                a = a + (b_outer.x * b_inner.x);
    
                println!(
                    "    x:{}, y:{}, v:{}, a:{}",
                    b_inner.x,
                    b_inner.y,
                    b_inner.v.get(),
                    a
                );
            }
    
            b_outer.v.set(a);
        }
    }
    

    It produces the same output as the C# program above. The "downside" is that whenever you want to work with v, you need use get() or into_inner(). There may be other downsides I'm not aware of.

提交回复
热议问题