On mut semantic for ownership

George Shuklin
journey to rust
Published in
2 min readAug 29, 2022

I’ve just solved a problem at Leetcode with following signature:

pub fn num_islands(grid: Vec<Vec<char>>) -> i32

When I solved it I changed it to:

pub fn num_islands(mut grid: Vec<Vec<char>>) -> i32 {

…and I used ‘mut’ for real, I modified grid instead of using Queue or something like this (I peeked into others solutions after I solved it).

Was I cheating? I believe I wasn’t. And the reason is that signature here is very explicit: I get ownership of the grid. There are no other users of those data, and data are deallocated at the end of my function. I HAVE OWNERSHIP.

Therefore, according to ownership idea, I can modify it. It someone want me not modify, they can give me non-mut borrow to data, and then I obliged to keep data intact.

But with ownership, it’s at my taste to modify data or not.

This is not excuses post.

This is once more, the post of awe for Rust type system. It’s expressiveness is really stunning. The signature is very clear on what are expectations and what is permitted, and those permissions and expectations are enforced!

Just compare this with ‘python3’ version:

class Solution:
def numIslands(self, grid: List[List[str]]) -> int:

Can I modify grid? Are there any other users for grid? May be there is some other thread doing the same problem with different algo?

Fear. What if I break something?
Uncertainty. Are there other users for data? What is the contract?
Doubt. May be I shouldn’t touch those data. I should be careful.

FUD-typed language, I suppose. In python2 it is even more hilarious, as there is no signature at all:

class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""

--

--

George Shuklin
journey to rust

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.