Help on invalid use of mutating method on rvalue

environment

  • magic 07.2 h
  • mojo 25.2.0

I have a simple Client struct. I need to store instances of Client in a dictionary.
But when I try to call a set method (set_var) which changes data, compiler reports error :
invalid call to ‘set_var’: invalid use of mutating method on rvalue of type ‘Client’

if I use a List in place of dictionary, there is no error.

How can I set mutable to be able to call setter ?

Here is a sample code :

sample.mojo

from collections import Dict
from collections import List

@value
struct Client[]():
    var var01: Int

    fn __init__(out self, var01: Int):
        self.var01 = var01
    
    def set_var(mut self, var01: Int):
        self.var01 = var01
    
    def get_var(self) -> Int:
        return self.var01


def main():
    var l01 = List[Client]()

    l01.append(Client(1))
    l01[0].set_var(2)
    
    print(l01[0].get_var()) # Ok print 2

    var d01 = Dict[String, List[Client]]()
    d01['ClientA'] = List[Client]()
    d01['ClientA'].append(Client(3))
    d01['ClientA'][0].set_var(4) # error invalid use of mutating method on rvalue


I’m not sure exactly what is the cause here, hopefully someone else can elaborate on that.

I think that one of Dict.__getitem__ or List.__getitem__ is actually creating a copy of the Client, which is the rvalue that the the message refers to. Since the rvalue isn’t bound to anything, mutating it doesn’t do anything, and that’s an error (I think my terminology here is a bit messy).

To fix it you just need to get a pointer to the dictionary value, for example:
d01.get_ptr("ClientA").value()[][0].set_var(4) fixes it.

Thanks for yours explanation and solution.

1 Like