Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between set_ and mutable_ methods in protobuf file

I have below sample protobuf file, which contains following methods could you please help me to understand when to use set_name() and when to use mutable_name(). As per my understanding both methods sets value to name field.

  inline void set_name(const char* value);
  inline ::std::string* mutable_name();
like image 838
Sumo Avatar asked Feb 22 '26 23:02

Sumo


2 Answers

std::string* mutable_name() does not set something. Perhaps you refer to a call like *mutable_name() = "blabla";. If this was the only usage then it would do the same as set_name, but it is not the only usage. mutable_name returns a pointer that can be stored and used later to set the name.

For illustration I will use a toy model:

#include <string>

struct named_thing {
     std::string name;
     void set(const std::string n) { name = n; }
     std::string* get_mutable() { return &name; }
};

The set method you can use to set the name. I suppose it's clear how to use it. The get_mutable on the other hand can be used to set the string at some later point. You could write a custom class that stores the pointer:

 struct name_setter {
     std::string* name = nullptr;
     void set(const std::string& n) { *name = n; }
     void rebind(std::string* n) { name = n; }
 };

name_setter does not need the whole named_thing, it only needs a std::string* to set it.

int main() {
   named_thing foo{ "foo" };
   name_setter bar{ &foo.name };
   bar.set("bar");
}
like image 83
463035818_is_not_a_number Avatar answered Feb 25 '26 13:02

463035818_is_not_a_number


When you need to modify a member variable that is a struct, using set_xxx() requires you to construct a struct instance beforehand and pass it in. On the other hand, if you use mutable_xxx(), you can simply call mutable_xxx() to obtain a raw pointer and modify it, which is particularly useful when you need to modify a specific part of the variable. For example, you can use the syntax mutable_xxx()->mutable_xxx_part()->mutable_xxx_field() = xxx to modify a specific field within the struct. The use of mutable_xxx has lower overhead compared to set_xxx in this situation.

like image 28
mariolu Avatar answered Feb 25 '26 12:02

mariolu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!