Comments (6)
Certainly. You just need to define two traits:
trait Data {
fn accept<V: Visitor>(&self, visitor: &mut V) -> V::Result;
}
trait Visitor {
type Result;
fn visit_stmt(&mut self, stmt: &Stmt) -> Self::Result;
fn visit_name(&mut self, name: &Name) -> Self::Result;
fn visit_expr(&mut self, expr: &Expr) -> Self::Result;
}
impl Data for Stmt {
fn accept<V: Visitor>(&self, visitor: &mut V) -> V::Result {
visitor.visit_stmt(self)
}
}
impl Data for Name {
fn accept<V: Visitor>(&self, visitor: &mut V) -> V::Result {
visitor.visit_name(self)
}
}
impl Data for Expr {
fn accept<V: Visitor>(&self, visitor: &mut V) -> V::Result {
visitor.visit_expr(self)
}
}
impl Visitor for Interpreter {
fn visit_stmt(&mut self, stmt: &Stmt) -> Self::Result { unimplemented!() }
fn visit_name(&mut self, name: &Name) -> Self::Result { unimplemented!() }
fn visit_expr(&mut self, expr: &Expr) -> Self::Result { unimplemented!() }
}
Serde uses visitors in this way to decouple serialization/deserialization from the data format.
from patterns.
Follow up question. With specialization you implement the visitor pattern similar to this:
#![feature(specialization)]
pub trait Visitor<T> {
fn visit(&mut self, t:&T);
}
pub trait Visitable: Sized {
fn accept<T>(&self, t: &mut T) where T: Visitor<Self> {
t.visit(self);
}
}
struct Expr;
impl Visitable for Expr {}
struct Term;
impl Visitable for Term {}
struct Vis;
impl <T> Visitor<T> for Vis where T: Visitable{
default fn visit(&mut self, _: &T) {
unimplemented!();
}
}
impl Visitor<Expr> for Vis {
fn visit(&mut self, _: &Expr) {
println!("Visiting an Expression");
}
}
impl Visitor<Term> for Vis {
fn visit(&mut self, _: &Term) {
println!("Visiting a Term");
}
}
fn main() {
let mut v = Vis;
Expr.accept(&mut v);
Term.accept(&mut v);
}
What are the thoughts on doing something like this vs creating a visit_*
for each method that is needed?
from patterns.
That's clever! In fact, if you don't need a default visit
implementation, you don't even need specialization: you can remove the impl<T> Visitor<T> for Vis
and it will work so long as Visitor<X>
is implemented for each visitable X
.
What's particular about that technique, as opposed to traditional visitors, is that an external crate could add a new Visitable
type (let's call it X
) and could implement Visitor<X>
for a new or an existing visitor (you can't do something like that on existing types with interfaces in Java or .NET) or just fall back to the default, if it's present.
Another interesting fact is that if you control the value to be visited and you provide your own visitor, then you only need to implement the Visitor<X>
traits you actually use.
A disadvantage of that technique is that it's harder to make a trait object for a Visitor
that supports all visitable types: you'll have to define a new trait that has each Visitor<X>
as a supertrait. For example:
pub trait Visitor2
where
Self: Visitor<Expr>,
Self: Visitor<Term>,
{
}
impl<T> Visitor2 for T
where
T: Visitor<Expr>,
T: Visitor<Term>,
{
}
Then the bound T: ?Sized
needs to be added to Visitable::accept
for the trait object to be accepted.
from patterns.
An issue with using generics here is that you can't invoke Visitable::accept
in a dyn Visitable
, so the dispatch is only dynamic in one argument (the Visitor
). With the named visit_xyz()
methods, you can start with a dyn Visitable
and a dyn Visitor
, as in
let vs: &[&dyn Visitor] = &[&V0, &V1];
let ds: &[&dyn Data] = &[&Stmt, &Name, &Expr];
for d in ds {
for v in vs {
d.accept(*v);
}
}
One can easily add new visitors, but adding new data requires adding methods to the Visitor
trait. This is essentially the same situation as using enum Data {Stmt, Name, Expr}
, albeit different syntax.
I'm not aware of a safe way to do dynamic multiple dispatch that is extensible in both arguments. This comment by Graydon Hoare (and the whole post above) offers some insight into the design decision: https://graydon2.dreamwidth.org/189377.html?thread=627649#cmt627649
Note that Julia inherits a CLOS-style object model with fully extensible multimethods.
from patterns.
Following my comment on HN it would be great to specify use cases when the visitor pattern should be used. Most of the time, pattern matching should be good enough and is more idiomatic Rust.
from patterns.
Changed the title of the issue because visitor pattern exists here
from patterns.
Related Issues (20)
- Floating Point Related Idioms HOT 1
- Add double panic mentioning for RAII guards HOT 1
- Clarify parts of Lenses and Prisms chapter HOT 11
- Borrow Checker Patterns HOT 2
- Clarify paragraph in Generics as Type Classes
- Clarify naming convention of `build()` in section 3.2.1 HOT 1
- Design Patterns, Strategy has unclear identifier `Context` and `run` mentioned. HOT 1
- View type
- Translations HOT 6
- Incorrect text in Command pattern description
- Translation: Persian HOT 5
- Is this example wrong ? HOT 1
- Printing the book should not inherit theme colours HOT 1
- Extract code into runnable Rust files HOT 4
- Translate: Vietnamese HOT 2
- Typo in idioms/coercion-arguments.md HOT 3
- Add pdf renderer and link rendered book
- Consistent Headline Capitalization? HOT 1
- Incompatible definition of Mutex::lock (or MutexGuard)
- Foo Bar (ad nauseam)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from patterns.