What does the ".." in https://github.com/servo/html5ever/blob/master/html5ever/examples/html2html.rs#L33 mean ?
let opts = ParseOpts {
tree_builder: TreeBuilderOpts {
drop_doctype: true,
..Default::default()
},
..Default::default()
};
I am not familiar with this notation.
it's called struct update syntax and can be used to take the values of other unspecified fields from a base starting object (in this case, a default)
https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
1 Like
Ah, so the first one says:
take a TreeBuilderfOpts default, and set the drop_doctype
filed to true
whilethe second one says:
take a ParseOPts default, and set the tree_builder
field to the value above?
According to the Rust Reference, this is called "struct base" notation. I've also heard it referred to as a "functional update" or "immutable update", since this is a common feature of languages that don't have support for mutation.
It takes an expression of the same type as the struct itself (meaning that, in your example, the impl Default for TreeBuilderOpts
is used), and fills in all of the fields except the explicitly named one.
1 Like
Yep, exactly.
Together with the field init shorthand (described immediately above) these two mechanisms can greatly reduce the boilerplate and verbosity of code, especially for things like the builder pattern. Rough Eg:
fn with_foo(self, foo) -> Self { // consumed
Self {
foo,
..self
}
}
3 Likes