How does Rust's struct hold and use a object? - rust

I need to use a struct to hold a serde_json object, and use it later.
extern crate serde_json;
use serde_json::builder::ObjectBuilder;
struct MyStruct {
builder: ObjectBuilder,
}
impl MyStruct {
fn new() -> MyStruct {
MyStruct { builder: ObjectBuilder::new() }
}
fn add_string_member(&self, name: &str, value: &str) {
self.builder.insert(name, value); //here compile error
}
}
fn main() {
let s = MyStruct::new();
s.add_string_member("name", "value");
}
But I get the error
error: cannot move out of borrowed content [E0507]

The methods in ObjectBuilder take self by value. Since you can't move something out of a borrowed pointer, the easy solution is to make your methods on MyStruct take self by value as well.
Also, ObjectBuilder's methods return a new ObjectBuilder with the changes. You can wrap that return value into a new MyStruct, which you can return from your methods.
extern crate serde_json;
use serde_json::builder::ObjectBuilder;
struct MyStruct {
builder: ObjectBuilder,
}
impl MyStruct {
fn new() -> MyStruct {
MyStruct { builder: ObjectBuilder::new() }
}
fn add_string_member(self, name: &str, value: &str) -> MyStruct {
MyStruct { builder: self.builder.insert(name, value) }
}
}
fn main() {
let s = MyStruct::new();
let s = s.add_string_member("name", "value");
}
If MyStruct also contains other members that you'd like to carry on into the new MyStruct, you can use a shortcut syntax to initialize the remaining fields of MyStruct from an existing instance:
fn add_string_member(self, name: &str, value: &str) -> MyStruct {
MyStruct { builder: self.builder.insert(name, value), ..self }
}
Here, the builder field of the new MyStruct will be set to the specified expression, and all other fields will be moved from self. (The .. syntax accepts any expression of the proper type, not just self.)

Related

How do I create a long-lived reference into a collection that I know will no longer be modified?

I'm implementing a bytecode VM and am struggling referencing data stored in a parsed representation of the bytecode. As is the nature of (most) bytecode, it and thus its parsed representation remain unmodified once it's initialized. A separate Vm contains the mutable parts (stack etc.) along with that module. I made an MCVE with additional explanatory comments to illustrate the problem; it's at the bottom and on the playground. The parsed bytecode may look like this:
Module { struct_types: {"Bar": StructType::Named(["a", "b"])} }
The strings "Bar", "a", "b" are references into the bytecode and have lifetime 'b, so we also have lifetimes in the types Module<'b> and StructType<'b>.
After creating this, I will want to create struct instances, think let bar = Bar { a: (), b: () };. At least currently, each struct instance needs to hold a reference to its type, so that type might look like this:
pub struct Struct<'b> {
struct_type: &'b bytecode::StructType<'b>,
fields: Vec<Value<'b>>,
}
The values of a struct's fields may be constants whose value is stored in the bytecode, so the Value enum has a lifetime 'b as well, and that works. The problem is that I have a &'b bytecode::StructType<'b> in the first field: how do I get a reference that lives long enough? I think the reference would actually be valid long enough.
The part of the code that I suspect to be the critical one is here:
pub fn struct_type(&self, _name: &str) -> Option<&'b StructType<'b>> {
// self.struct_types.get(name)
todo!("fix lifetime problems")
}
With the commented out code, I can't get a 'b reference because the reference self.struct_types lives too short; to fix that I'd need to do &'b self which would spread virally through the code; also, most of the times I need to borrow the Vm mutably, which doesn't work if all those exclusive self references have to live long.
Introducing a separate lifetime 'm so that I could return a &'m StructType<'b> sounds like something that I could try as well, but that sounds just as viral and in addition introduces a separate lifetime I need to keep track of; being able to replace 'b with 'm (or at least only having on in each place) would be a bit nicer.
Finally this feels like something that pinning could be helpful with, but I don't understand that topic enough to make an educated guess on how that could be approached.
MCVE
#![allow(dead_code)]
mod bytecode {
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StructType<'b> {
/// unit struct type; doesn't have fields
Empty,
/// tuple struct type; fields are positional
Positional(usize),
/// "normal" struct type; fields are named
Named(Vec<&'b str>),
}
impl<'b> StructType<'b> {
pub fn field_count(&self) -> usize {
match self {
Self::Empty => 0,
Self::Positional(field_count) => *field_count,
Self::Named(fields) => fields.len(),
}
}
}
#[derive(Debug, Clone)]
pub struct Module<'b> {
struct_types: BTreeMap<&'b str, StructType<'b>>,
}
impl<'b> Module<'b> {
// here is the problem: I would like to return a reference with lifetime 'b.
// from the point I start executing instructions, I know that I won't modify
// the module (particularly, I won't add entries to the map), so I think that
// lifetime should be possible - pinning? `&'b self` everywhere? idk
pub fn struct_type(&self, _name: &str) -> Option<&'b StructType<'b>> {
// self.struct_types.get(name)
todo!("fix lifetime problems")
}
}
pub fn parse<'b>(bytecode: &'b str) -> Module<'b> {
// this would use nom to parse actual bytecode
assert_eq!(bytecode, "struct Bar { a, b }");
let bar = &bytecode[7..10];
let a = &bytecode[13..14];
let b = &bytecode[16..17];
let fields = vec![a, b];
let bar_struct = StructType::Named(fields);
let struct_types = BTreeMap::from_iter([
(bar, bar_struct),
]);
Module { struct_types }
}
}
mod vm {
use crate::bytecode::{self, StructType};
#[derive(Debug, Clone)]
pub enum Value<'b> {
Unit,
Struct(Struct<'b>),
}
#[derive(Debug, Clone)]
pub struct Struct<'b> {
struct_type: &'b bytecode::StructType<'b>,
fields: Vec<Value<'b>>,
}
impl<'b> Struct<'b> {
pub fn new(struct_type: &'b bytecode::StructType<'b>, fields: Vec<Value<'b>>) -> Self {
Struct { struct_type, fields }
}
}
#[derive(Debug, Clone)]
pub struct Vm<'b> {
module: bytecode::Module<'b>,
}
impl<'b> Vm<'b> {
pub fn new(module: bytecode::Module<'b>) -> Self {
Self { module }
}
pub fn create_struct(&mut self, type_name: &'b str) -> Value<'b> {
let struct_type: &'b StructType<'b> = self.module.struct_type(type_name).unwrap();
// just initialize the fields to something, we don't care
let fields = vec![Value::Unit; struct_type.field_count()];
let value = Value::Struct(Struct::new(struct_type, fields));
value
}
}
}
pub fn main() {
// the bytecode contains all constants needed at runtime;
// we're just interested in how struct types are handled
// obviously the real bytecode is not as human-readable
let bytecode = "struct Bar { a, b }";
// we parse that into a module that, among other things,
// has a map of all struct types
let module = bytecode::parse(bytecode);
println!("{:?}", module);
// we create a Vm that is capable of running commands
// that are stored in the module
let mut vm = vm::Vm::new(module);
// now we try to execute an instruction to create a struct value
// the instruction for this contains a reference to the type name
// stored in the bytecode.
// the struct value contains a reference to its type and holds its field values.
let value = {
let bar = &bytecode[7..10];
vm.create_struct(bar)
};
println!("{:?}", value);
}
&'b bytecode::StructType<'b> is a classic anti-pattern in Rust, it strongly indicates incorrectly annotated lifetimes. It doesn't make sense that an object would depend on some lifetime and borrowing it creates the same lifetime. That is very rare to happen on purpose.
So I suspect you need two lifetimes, which I will call 'm and 'b:
'b: the lifetime of the bytecode string, everything that references it will use &'b str.
'm: the lifetime of the Module object. Everything that references it or its contained StructType will use this lifetime.
If split into two lifetimes and adjusted correctly, it simply works:
#![allow(dead_code)]
mod bytecode {
use std::{collections::BTreeMap, iter::FromIterator};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StructType<'b> {
/// unit struct type; doesn't have fields
Empty,
/// tuple struct type; fields are positional
Positional(usize),
/// "normal" struct type; fields are named
Named(Vec<&'b str>),
}
impl<'b> StructType<'b> {
pub fn field_count(&self) -> usize {
match self {
Self::Empty => 0,
Self::Positional(field_count) => *field_count,
Self::Named(fields) => fields.len(),
}
}
}
#[derive(Debug, Clone)]
pub struct Module<'b> {
struct_types: BTreeMap<&'b str, StructType<'b>>,
}
impl<'b> Module<'b> {
// here is the problem: I would like to return a reference with lifetime 'b.
// from the point I start executing instructions, I know that I won't modify
// the module (particularly, I won't add entries to the map), so I think that
// lifetime should be possible - pinning? `&'b self` everywhere? idk
pub fn struct_type(&self, name: &str) -> Option<&StructType<'b>> {
self.struct_types.get(name)
}
}
pub fn parse<'b>(bytecode: &'b str) -> Module<'b> {
// this would use nom to parse actual bytecode
assert_eq!(bytecode, "struct Bar { a, b }");
let bar = &bytecode[7..10];
let a = &bytecode[13..14];
let b = &bytecode[16..17];
let fields = vec![a, b];
let bar_struct = StructType::Named(fields);
let struct_types = BTreeMap::from_iter([(bar, bar_struct)]);
Module { struct_types }
}
}
mod vm {
use crate::bytecode::{self, StructType};
#[derive(Debug, Clone)]
pub enum Value<'b, 'm> {
Unit,
Struct(Struct<'b, 'm>),
}
#[derive(Debug, Clone)]
pub struct Struct<'b, 'm> {
struct_type: &'m bytecode::StructType<'b>,
fields: Vec<Value<'b, 'm>>,
}
impl<'b, 'm> Struct<'b, 'm> {
pub fn new(struct_type: &'m bytecode::StructType<'b>, fields: Vec<Value<'b, 'm>>) -> Self {
Struct {
struct_type,
fields,
}
}
}
#[derive(Debug, Clone)]
pub struct Vm<'b> {
module: bytecode::Module<'b>,
}
impl<'b> Vm<'b> {
pub fn new(module: bytecode::Module<'b>) -> Self {
Self { module }
}
pub fn create_struct(&mut self, type_name: &str) -> Value<'b, '_> {
let struct_type: &StructType<'b> = self.module.struct_type(type_name).unwrap();
// just initialize the fields to something, we don't care
let fields = vec![Value::Unit; struct_type.field_count()];
let value = Value::Struct(Struct::new(struct_type, fields));
value
}
}
}
pub fn main() {
// the bytecode contains all constants needed at runtime;
// we're just interested in how struct types are handled
// obviously the real bytecode is not as human-readable
let bytecode = "struct Bar { a, b }";
// we parse that into a module that, among other things,
// has a map of all struct types
let module = bytecode::parse(bytecode);
println!("{:?}", module);
// we create a Vm that is capable of running commands
// that are stored in the module
let mut vm = vm::Vm::new(module);
// now we try to execute an instruction to create a struct value
// the instruction for this contains a reference to the type name
// stored in the bytecode.
// the struct value contains a reference to its type and holds its field values.
let value = {
let bar = &bytecode[7..10];
vm.create_struct(bar)
};
println!("{:?}", value);
}
Module { struct_types: {"Bar": Named(["a", "b"])} }
Struct(Struct { struct_type: Named(["a", "b"]), fields: [Unit, Unit] })
It can further be simplified, however, due to the fact that 'm is connected to 'b, and therefore everything that depends on 'm automatically also has access to 'b objects, because 'b is guaranteed to outlive 'm.
Therefore, let's introduce 'a, which we will now use inside of the vm mod to reference anything from the bytecode mod. This will further allow lifetime elysion to happen at a couple of points, simplifying the code even further:
#![allow(dead_code)]
mod bytecode {
use std::{collections::BTreeMap, iter::FromIterator};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StructType<'b> {
/// unit struct type; doesn't have fields
Empty,
/// tuple struct type; fields are positional
Positional(usize),
/// "normal" struct type; fields are named
Named(Vec<&'b str>),
}
impl<'b> StructType<'b> {
pub fn field_count(&self) -> usize {
match self {
Self::Empty => 0,
Self::Positional(field_count) => *field_count,
Self::Named(fields) => fields.len(),
}
}
}
#[derive(Debug, Clone)]
pub struct Module<'b> {
struct_types: BTreeMap<&'b str, StructType<'b>>,
}
impl<'b> Module<'b> {
// here is the problem: I would like to return a reference with lifetime 'b.
// from the point I start executing instructions, I know that I won't modify
// the module (particularly, I won't add entries to the map), so I think that
// lifetime should be possible - pinning? `&'b self` everywhere? idk
pub fn struct_type(&self, name: &str) -> Option<&StructType<'b>> {
self.struct_types.get(name)
}
}
pub fn parse<'b>(bytecode: &'b str) -> Module<'b> {
// this would use nom to parse actual bytecode
assert_eq!(bytecode, "struct Bar { a, b }");
let bar = &bytecode[7..10];
let a = &bytecode[13..14];
let b = &bytecode[16..17];
let fields = vec![a, b];
let bar_struct = StructType::Named(fields);
let struct_types = BTreeMap::from_iter([(bar, bar_struct)]);
Module { struct_types }
}
}
mod vm {
use crate::bytecode::{self, StructType};
#[derive(Debug, Clone)]
pub enum Value<'a> {
Unit,
Struct(Struct<'a>),
}
#[derive(Debug, Clone)]
pub struct Struct<'a> {
struct_type: &'a bytecode::StructType<'a>,
fields: Vec<Value<'a>>,
}
impl<'a> Struct<'a> {
pub fn new(struct_type: &'a bytecode::StructType, fields: Vec<Value<'a>>) -> Self {
Struct {
struct_type,
fields,
}
}
}
#[derive(Debug, Clone)]
pub struct Vm<'a> {
module: bytecode::Module<'a>,
}
impl<'a> Vm<'a> {
pub fn new(module: bytecode::Module<'a>) -> Self {
Self { module }
}
pub fn create_struct(&mut self, type_name: &str) -> Value {
let struct_type: &StructType = self.module.struct_type(type_name).unwrap();
// just initialize the fields to something, we don't care
let fields = vec![Value::Unit; struct_type.field_count()];
let value = Value::Struct(Struct::new(struct_type, fields));
value
}
}
}
pub fn main() {
// the bytecode contains all constants needed at runtime;
// we're just interested in how struct types are handled
// obviously the real bytecode is not as human-readable
let bytecode = "struct Bar { a, b }";
// we parse that into a module that, among other things,
// has a map of all struct types
let module = bytecode::parse(bytecode);
println!("{:?}", module);
// we create a Vm that is capable of running commands
// that are stored in the module
let mut vm = vm::Vm::new(module);
// now we try to execute an instruction to create a struct value
// the instruction for this contains a reference to the type name
// stored in the bytecode.
// the struct value contains a reference to its type and holds its field values.
let value = {
let bar = &bytecode[7..10];
vm.create_struct(bar)
};
println!("{:?}", value);
}
Module { struct_types: {"Bar": Named(["a", "b"])} }
Struct(Struct { struct_type: Named(["a", "b"]), fields: [Unit, Unit] })
Fun fact: This is now one of the rare cases where we legitimately have to use &'a bytecode::StructType<'a>, so take my opening statement with a grain of salt, and you were kind of right all along :)
The crazy thing is if we then rename 'a to 'b to be consistent with your original code, we get almost your code with only some minor differences:
#![allow(dead_code)]
mod bytecode {
use std::{collections::BTreeMap, iter::FromIterator};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StructType<'b> {
/// unit struct type; doesn't have fields
Empty,
/// tuple struct type; fields are positional
Positional(usize),
/// "normal" struct type; fields are named
Named(Vec<&'b str>),
}
impl<'b> StructType<'b> {
pub fn field_count(&self) -> usize {
match self {
Self::Empty => 0,
Self::Positional(field_count) => *field_count,
Self::Named(fields) => fields.len(),
}
}
}
#[derive(Debug, Clone)]
pub struct Module<'b> {
struct_types: BTreeMap<&'b str, StructType<'b>>,
}
impl<'b> Module<'b> {
// here is the problem: I would like to return a reference with lifetime 'b.
// from the point I start executing instructions, I know that I won't modify
// the module (particularly, I won't add entries to the map), so I think that
// lifetime should be possible - pinning? `&'b self` everywhere? idk
pub fn struct_type(&self, name: &str) -> Option<&StructType<'b>> {
self.struct_types.get(name)
}
}
pub fn parse<'b>(bytecode: &'b str) -> Module<'b> {
// this would use nom to parse actual bytecode
assert_eq!(bytecode, "struct Bar { a, b }");
let bar = &bytecode[7..10];
let a = &bytecode[13..14];
let b = &bytecode[16..17];
let fields = vec![a, b];
let bar_struct = StructType::Named(fields);
let struct_types = BTreeMap::from_iter([(bar, bar_struct)]);
Module { struct_types }
}
}
mod vm {
use crate::bytecode::{self, StructType};
#[derive(Debug, Clone)]
pub enum Value<'b> {
Unit,
Struct(Struct<'b>),
}
#[derive(Debug, Clone)]
pub struct Struct<'b> {
struct_type: &'b bytecode::StructType<'b>,
fields: Vec<Value<'b>>,
}
impl<'b> Struct<'b> {
pub fn new(struct_type: &'b bytecode::StructType, fields: Vec<Value<'b>>) -> Self {
Struct {
struct_type,
fields,
}
}
}
#[derive(Debug, Clone)]
pub struct Vm<'b> {
module: bytecode::Module<'b>,
}
impl<'b> Vm<'b> {
pub fn new(module: bytecode::Module<'b>) -> Self {
Self { module }
}
pub fn create_struct(&mut self, type_name: &str) -> Value {
let struct_type: &StructType = self.module.struct_type(type_name).unwrap();
// just initialize the fields to something, we don't care
let fields = vec![Value::Unit; struct_type.field_count()];
let value = Value::Struct(Struct::new(struct_type, fields));
value
}
}
}
pub fn main() {
// the bytecode contains all constants needed at runtime;
// we're just interested in how struct types are handled
// obviously the real bytecode is not as human-readable
let bytecode = "struct Bar { a, b }";
// we parse that into a module that, among other things,
// has a map of all struct types
let module = bytecode::parse(bytecode);
println!("{:?}", module);
// we create a Vm that is capable of running commands
// that are stored in the module
let mut vm = vm::Vm::new(module);
// now we try to execute an instruction to create a struct value
// the instruction for this contains a reference to the type name
// stored in the bytecode.
// the struct value contains a reference to its type and holds its field values.
let value = {
let bar = &bytecode[7..10];
vm.create_struct(bar)
};
println!("{:?}", value);
}
Module { struct_types: {"Bar": Named(["a", "b"])} }
Struct(Struct { struct_type: Named(["a", "b"]), fields: [Unit, Unit] })
So the actual fix for your original code is as follows:
4c4
< use std::collections::BTreeMap;
---
> use std::{collections::BTreeMap, iter::FromIterator};
36,38c36,37
< pub fn struct_type(&self, _name: &str) -> Option<&'b StructType<'b>> {
< // self.struct_types.get(name)
< todo!("fix lifetime problems")
---
> pub fn struct_type(&self, name: &str) -> Option<&StructType<'b>> {
> self.struct_types.get(name)
73c72
< pub fn new(struct_type: &'b bytecode::StructType<'b>, fields: Vec<Value<'b>>) -> Self {
---
> pub fn new(struct_type: &'b bytecode::StructType, fields: Vec<Value<'b>>) -> Self {
91,92c90,91
< pub fn create_struct(&mut self, type_name: &'b str) -> Value<'b> {
< let struct_type: &'b StructType<'b> = self.module.struct_type(type_name).unwrap();
---
> pub fn create_struct(&mut self, type_name: &str) -> Value {
> let struct_type: &StructType = self.module.struct_type(type_name).unwrap();
I hope deriving them step by step made it somewhat clear why those changes are necessary.

Rust: How to return a reference to an Rc<RefCell<HashMap<K, V>> value?

I'm trying to learn Rust and I'm having some problems with different smart pointers and stuff.
Here is my code:
pub struct MyMap<T> {
map: Rc<RefCell<HashMap<String, T>>>,
}
impl <T> MyMap<T> {
// Not entire sure if it's supposed to be Option<Ref<T>> or something else here.
pub fn get(&self, key: &str) -> Option<Ref<T>> {
todo!("What do I do here?")
}
}
The closest I've got is by searching the HashMap twice:
impl <T> MyMap<T> {
pub fn get(&self, key: &str) -> Option<Ref<T>> {
if self.map.borrow().contains_key(key) {
Some(Ref::map(self.map.borrow(), |m| m.get(key).unwrap()))
} else {
None
}
}
}
Which isn't very elegant to say the least.
Two solutions that come to my mind:
Use the unstable Ref::filter_map, which will potentially be stabilized in 1.63.0.
Use a context manager pattern, which circumvents the entire problem.
filter_map:
#![feature(cell_filter_map)]
use std::{
cell::{Ref, RefCell},
collections::HashMap,
rc::Rc,
};
pub struct MyMap<T> {
map: Rc<RefCell<HashMap<String, T>>>,
}
impl<T> MyMap<T> {
pub fn get(&self, key: &str) -> Option<Ref<T>> {
Ref::filter_map(self.map.borrow(), |map| map.get(key)).ok()
}
}
fn main() {
let map: MyMap<u32> = MyMap {
map: Rc::new(RefCell::new(HashMap::from([
("meaning".to_string(), 42),
("nice".to_string(), 69),
]))),
};
println!("{:?}", map.get("meaning"));
}
Some(42)
Context manager:
The idea here is that instead of returning a reference, you pass in a closure of the action that needs the value. That entirely circumvents the lifetime problem, because the variables inside of the get (or with_value in the example below) are still in scope while the closure gets executed.
use std::{cell::RefCell, collections::HashMap, rc::Rc};
pub struct MyMap<T> {
map: Rc<RefCell<HashMap<String, T>>>,
}
impl<T> MyMap<T> {
pub fn with_value<F, O>(&self, key: &str, f: F) -> O
where
F: FnOnce(Option<&T>) -> O,
{
f(self.map.borrow().get(key))
}
}
fn main() {
let map: MyMap<u32> = MyMap {
map: Rc::new(RefCell::new(HashMap::from([
("meaning".to_string(), 42),
("nice".to_string(), 69),
]))),
};
map.with_value("meaning", |value| {
println!("{:?}", value);
});
}
Some(42)

How to impl ops::Deref for an struct wrapped in a Mutex

When using a Arc<Mutex<>> wrapper for a struct, is it possible to deref the wrapper into one of the internal structs fields? In this case I want to deref my PersonWrapper struct into a String from the inner PersonStruct "name" field.
use std::sync::{Mutex, Arc};
pub struct PersonWrapper{
inner: Arc<Mutex<Person>>
}
impl PersonWrapper{
pub fn new(name: String, age: i32,)->Self{
PersonWrapper{
inner: Arc::new(Mutex::new(Person::new(name, age)))
}
}
}
pub struct Person{
name: String,
age: i32,
}
impl Person{
pub fn new(name: String, age: i32)->Self{
Person{
name,
age,
}
}
}
impl std::ops::Deref for PersonWrapper{
type Target = String;
fn deref(&self) -> &Self::Target {
&self.inner.into_inner().unwrap().name
// &self.inner.lock().unwrap().node_id.clone()
}
}
fn main(){
let wrapped_person = PersonWrapper::new(String::from("Zondo"), 45);
assert_eq!(*wrapped_person, String::from("Zondo"));
}
gives errors:
error[E0515]: cannot return reference to temporary value
&self.inner.into_inner().unwrap().name
^--------------------------------^^^^^
||
|temporary value created here
returns a reference to data owned by the current function
error[E0507]: cannot move out of an `Arc`
&self.inner.into_inner().unwrap().name
^^^^^^^^^^ move occurs because value has type `Mutex<Person>`, which does not implement the `Copy` trait
Playground
If you need to provide convenient access to a part of data behind a Mutex, combining the locking and "projecting" (narrowing to a field), you can use the Mutex from the parking_lot crate. Among many other optimizations and improvements, it offers MutexGuard. For example:
use std::sync::Arc;
use parking_lot::{Mutex, MutexGuard, MappedMutexGuard};
pub struct PersonWrapper {
inner: Arc<Mutex<Person>>,
}
impl PersonWrapper {
pub fn new(name: String, age: i32) -> Self {
PersonWrapper {
inner: Arc::new(Mutex::new(Person::new(name, age))),
}
}
pub fn name(&self) -> MappedMutexGuard<String> {
MutexGuard::map(self.inner.lock(), |p| &mut p.name)
}
}
Now you can use name() as if it were a locked mutex that only held the name part of the Person:
let wrapped_person = PersonWrapper::new("Zondo".to_owned(), 45);
assert_eq!(&*wrapped_person.name(), "Zondo");
*wrapped_person.name() = "Mondo".to_owned();
assert_eq!(&*wrapped_person.name(), "Mondo");
Playground

Is it more conventional to pass-by-value or pass-by-reference when the method needs ownership of the value?

When I'm passing a object by reference to a struct's new() method, and the struct will own the object, is it more conventional to:
pass the object by reference, and do to_owned() in the new()
clone the object before calling new(), and pass by value, moving it
I can think of pros and cons of each in terms of clarity and separation-of-concerns.
#[derive(Clone)]
struct MyState;
struct MyStruct {
state: MyState,
}
impl MyStruct {
pub fn new_by_ref(state: &MyState) -> Self {
MyStruct {
state: state.to_owned(),
}
}
pub fn new_by_val(state: MyState) -> Self {
MyStruct { state }
}
}
fn main() {
let state1 = MyState;
let struct1 = MyStruct::new_by_ref(&state1);
let state2 = MyState;
let struct2 = MyStruct::new_by_val(state2.clone());
}
Pass by value.
This way, the program can avoid unnecessarily doubly-allocating the value if the caller no longer needs it.
In many cases, I recommend accepting anything that can be made into the owned type. This is easily demonstrated with String:
struct MyStruct {
state: String,
}
impl MyStruct {
fn new(state: impl Into<String>) -> Self {
let state = state.into();
MyStruct { state }
}
}
fn main() {
let struct1 = MyStruct::new("foo");
let struct2 = MyStruct::new(String::from("bar"));
}
See also:
How to accept str, String and &String in a single rust function

Is it possible to create a macro to implement builder pattern methods?

I have a builder pattern implemented for my struct:
pub struct Struct {
pub grand_finals_modifier: bool,
}
impl Struct {
pub fn new() -> Struct {
Struct {
grand_finals_modifier: false,
}
}
pub fn grand_finals_modifier<'a>(&'a mut self, name: bool) -> &'a mut Struct {
self.grand_finals_modifier = grand_finals_modifier;
self
}
}
Is it possible in Rust to make a macro for methods like this to generalize and avoid a lot of duplicating code? Something that we can use as the following:
impl Struct {
builder_field!(hello, bool);
}
After reading the documentation, I've come up with this code:
macro_rules! builder_field {
($field:ident, $field_type:ty) => {
pub fn $field<'a>(&'a mut self,
$field: $field_type) -> &'a mut Self {
self.$field = $field;
self
}
};
}
struct Struct {
pub hello: bool,
}
impl Struct {
builder_field!(hello, bool);
}
fn main() {
let mut s = Struct {
hello: false,
};
s.hello(true);
println!("Struct hello is: {}", s.hello);
}
It does exactly what I need: creates a public builder method with specified name, specified member and type.
To complement the already accepted answer, since it is 4 years old by now, you should check out the crate rust-derive-builder. It uses procedural macros to automatically implement the builder pattern for any struct.

Resources