Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In python you can't really statically define a reference count

   a = {}
   b = {}
   l = []
   for _ in range(100):
       if input('thingy'):
          l.append(a)
       else:
          l.append(b)
In that snippet it's impossible to know how many references there are to a or b.

In Rust, lifetime management is set up so that your code can statically determine when something no longer can be referred to (hence "free GC").

For example:

   def f():
      a = 3 
      g(a)
      # a is no longer used from this point
      return 5
you can clearly define when things are no longer usable, hence free-able. Python in this context will also free at the end of the function, but it's because it will be decrementing the reference counter and it gets to 0. But Rust won't need to have the reference counter since it knows it can free the object at any point after g.

(This isn't a great example for a lot of reasons, Rust allows you to go much further than this)

This ends up being somewhat similar to writing code in more statically typed languages/languages with dependent types. You might have to rework your code so that the machine can properly identify when it can free memory.



How then does Rust avoid the if('thingy') issue? Or, for that matter, a language like C, where presumably a and b would be allocated on the stack. In C would they both hang around until the function returns? Or would I have to copy them into the array anyway, which would be heap-allocated?


They're stack allocated in Rust too, so they're both going to stick around. Arrays in Rust are stack allocated, but this code would probably use a vector, which is heap allocated, and so yeah, you'd end up copying them from the stack to the heap.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: