Read and Modify
#
Read and Modify ResourceTo read and modify resource Rogue has two more built-in functions. Their names perfectly match their goals: borrow_global
and borrow_global_mut
.
borrow_global
#
Immutable borrow with In ownership and references chapter you've got to know mutable (&mut) and immutable references. It's time to put this knowledge to practice!
A lot has happened here. First, let's deal with method signature. Global function borrow_global<T>
gives a immutable reference to resource T. It's signature is like:
By using this function we get read access to resource stored at specific address. Which means that method has capability to read any of its resources at any addresses (if this functionality is implemented).
Another conclusion: due to borrow checking you cannot return reference to resource nor to its contents (as original reference to resource will die on scope end).
Since resource is a non-copyable type, it is impossible to use dereference operator '*' on it.
#
Acquires keywordThere's another detail worth explanation: keyword acquires
which is put after function return value. This keyword explicitly defines all the resources acquired by this function. You must specify each acqured resource, even if it's a nested function call actually acquires resource - parent scope must have this resource specified in acquires list.
Syntax for function with acquires
is like this:
borrow_global_mut
#
Mutable borrow with To get mutable reference to resource, add _mut
to your borrow_global
and that's all. Let's add a function to add new (currently empty) item to collection.
Mutable reference to resource allows creating mutable references to its contents. That is why we're able to modify inner vector items
in this example.
Signature for borrow_global_mut
is: