Friday, April 03, 2015

Graphs in Rust

Graphs are a bit awkward to construct in Rust because of Rust's stringent lifetime and mutability requirements. Graphs of objects are very common in OO programming. In this tutorial I'm going to go over a few different approaches to implementation. My preferred approach uses arena allocation and makes slightly advanced use of explicit lifetimes. I'll finish up by discussing a few potential Rust features which would make using such an approach easier.

There are essentially two orthogonal problems: how to handle the lifetime of the graph and how to handle it's mutability.

The first problem essentially boils down to what kind of pointer to use to point to other nodes in the graph. Since graph-like data structures are recursive (the types are recursive, even if the data is not) we are forced to use pointers of some kind rather than have a totally value-based structure. Since graphs can be cyclic, and ownership in Rust cannot be cyclic, we cannot use Box<Node> as our pointer type (as we might do for tree-like data structures or linked lists).

No graph is truly immutable. Because there may be cycles, the graph cannot be created in a single statement. Thus, at the very least, the graph must be mutable during its initialisation phase. The usual invariant in Rust is that all pointers must either be unique or immutable. Graph edges must be mutable (at least during initialisation) and there can be more than one edge into any node, thus no edges are guaranteed to be unique. So we're going to have to do something a little bit advanced to handle mutability.

...

Read the full tutorial, with examples. There's also some discussion of potential language improvements in Rust to make dealing with graphs easier.

33 comments:

Robert said...

Seems to me it would be really nice to have the option of saying "I don't care about managing lifetimes myself here, just use a tracing GC for all this stuff".

I know that was once part of the Rust plan, and then the plan was to push it out to a library with language support for tracing hooks, and it seems now the option has disappeared entirely. Which makes me sad.

Unknown said...

I just wrote a quick post showing another way to model graphs:

http://smallcultfollowing.com/babysteps/blog/2015/04/06/modeling-graphs-in-rust-using-vector-indices/

I would offer a slight correction to the previous commenter, though: the option of tracing Gc is not currently available, but it is something I hope we will work on soon.

gasche said...

In Mezzo, they use a dynamic mechanism called "adoption and abandon" as a way to handle shared/cyclic nodes in a relatively ergonomic way (but paying the cost of a runtime check when taking ownership of a node during traversal).

See for example this code example for graphs. Adoption and Abandon has been described in various places, such as this blog post.

Anonymous said...

A graph is just a tuple G = (V, E) where V is some set of vertices, and E a set of edges, generally represented as tuples of vertices. In general, either your vertices or your edges are implicit to some degree. And lots of things in your program form graphs with or without your awareness or intention. Becoming aware of hidden graph structures in your code is often an "ah-hah" moment.

There are tons of ways to represent graphs. There is no precondition that they be either pointer-based or dynamic. You can form graphs from anything that allows any kind of associativity: arrays, genejric maps, function calls (as mentioned above), match statements, etc.

The point is you have a set of "things", and you have a set of "pairs of things", where each item in a given pair is a "thing". If you have a set of "things", and *any* other structure in your code which associates pairs of "things", that forms a graph -- whether or not that is what you indended!

It's very easy to form static graphs. For example, you can represent vertices as functions, edges as calls from one function to another. Yes: every program consists of a graph over functions! You could represent nodes as enum values, and edges as match clauses. Whether or not you intend, this forms a graph.

It's not that hard, guys.

Sudheer Patel said...

Thanks for sharing this post. you can learn Online Hyperion Training here.

Travel company in delhi said...

What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much.

Jyotish said...

Hello,

Do you know? You are a very good and loyal friend, the information I was looking for on the Internet, I got it from your website and not only that, but I got much more information than I wanted. You have done your duty well as a blogger. I am proud of you, because you write articles for us, it helps us a lot and we get out of the place where we are stuck.

Really, whenever I read your articles, I like it so much that I cannot tell, because you have that talent which makes anyone crazy, I mean the words in your article are very true and are useful, that's why most people like to come to your website.

According to me, After reading the entire article, most people would have shared your article as well, because you give so much good knowledge to everyone that anyone would like to share your article.

Well, now let me go, I got pleasure by reading your article. Thanks a lot.

Ok Bye, Have a Wonderful Day. Findd Hindi

Jyotish Sahni said...

Hello,

"What a Fantastic Article is This"

Really, I found this article very helpful because there is a lot of beneficial and helpful information in this great article. I shared this article with my friends because it is very compulsory for reading as because of your truthful and honest content. Thank you for helping me find the information I needed.

Ok Bye, Have a Wonderful Day.

Regards,
Jyotish

How to Make a Better Comment on the Blog
What is the another name for Veda

Jyotish said...

Thanks for The Valuable & Fantastic Article 🙂.
FinddHindi is a great platform for learning knowledge about Internet and Technology.

learning.oilab said...

Thanks for sharing the article I always appreciate your topic. Python Training In Jodhpur

Finlock online said...

Such a very useful blog. Very Interesting to read this blog. Thanks for proving such a wonderful content. Cyber Insurance in india

AchieversIT said...

I really like you and This information is really very helpful. Thank you for sharing.
I will make sure to be reading your blog more. You made a good point Thanks!
if you want to learn UI Development Visit Our Website. https://www.achieversit.com/ui-development-training-course-institute-in-bangalore

periyannan said...

Thanks for sharing this unique information with us. Your post is really awesome. Your blog is really helpful for me..

artificial intelligence internship | best final year projects for cse | internship certificate online | internship for mba finance students | internship meaning in tamil

Alex Jarboe said...

Thanks for suggesting good list. I appreciate your work this is really helpful for everyone. Get more information at Splunk Training. Keep posting such useful information.

Anonymous said...


Interesting stuff to read. Keep it up.

SBI share price
Tata Steel Share Price
ITC Share Price
DLF share price
HDFC bank share price

Anonymous said...

One of the best article read so far! Well, if you are in need for Virtual assistant

emma jackson said...

This is a great post and have been looking for this since a long time. Well you can visit here if you are looking for software testing

4 said...

Loved it thanks for sharing
oracle scm online training

Ammy Anderson said...

We appreciate you sharing this special information with us. Your article is actually fantastic. I find your blog to be really beneficial. I would suggest Security Plus Training as a advanced skill.

bahu said...

One of the best article read so far!

bharath said...

This will be really helpful, thanks for sharing. will be waiting for more.

Anny Tech said...

Thank you for sharing the information.

Sameer said...

This will be really helpful, thanks for sharing.

Johan battler said...

Here is the detail of Watch Fox 505 Live Cricket World World Cup 2023 Streaming Free. Fox 505 Live is a very well-known channel for live broadcasting of sports, entertainment shows.

Cleaning Services Mooresville NC said...

Mooresville NC Cleaning Services offers professional cleaning solutions in the Mooresville area. Our team of experienced cleaners is dedicated to providing top-notch cleaning services for both residential and commercial properties. With our attention to detail and commitment to customer satisfaction, you can trust us to leave your space spotless and refreshed.

Whether you need regular cleaning services or a one-time deep clean, we have the expertise and resources to meet your needs. Contact Cleaning Services Mooresville NC today for a clean and healthy environment.

Roaming Routes. said...

Hosting prices in India offer remarkable value, accommodating the needs of a diverse range of businesses. With basic shared hosting plans starting from as low as ₹99 per month, businesses benefit from essential features such as sufficient storage, email accounts, and 24/7 customer support. For companies requiring greater resources and traffic management, VPS and dedicated hosting options are available, ranging from ₹1,000 to ₹10,000 per month. Many Indian hosting providers also bundle additional services like free domain registration, SSL certificates, and website builders at no extra cost. These competitively priced plans are designed to support businesses in launching and maintaining a professional online presence affordably and efficiently.
https://onohosting.com/

Budget Bytes said...

A nursing recruitment agency in India specializes in sourcing and placing highly skilled nursing professionals in various healthcare settings, both domestically and internationally. These agencies meticulously screen candidates to ensure they meet the highest standards of competence and care. They often provide additional training and certification to align with global healthcare requirements. With a vast network of hospitals, clinics, and care facilities, these agencies offer a plethora of opportunities for Indian nurses. They also assist with visa processing and relocation logistics, ensuring a smooth transition for candidates moving abroad. By bridging the gap between talent and demand, they play a pivotal role in addressing healthcare workforce shortages. Their services are crucial for maintaining the quality and efficiency of patient care across different medical institutions.
https://dynamichealthstaff.com/

Homeopathic Doctors in Delhi said...

Understanding the cost of breast surgery in Delhi involves evaluating several key factors. A lumpectomy, designed to remove only a portion of the breast tissue, ranges between INR 1,00,000 to INR 1,50,000. For more comprehensive procedures, such as a total mastectomy, expenses typically fall between INR 1,50,000 to INR 2,50,000. Advanced surgical interventions, like oncoplastic surgery that includes both tumour removal and cosmetic reconstruction, can be more costly. These costs generally encapsulate surgeon fees, anesthesia, and hospital charges. Additionally, patients should prepare for extra expenses related to pre-operative tests, post-operative care, and required medications. Financial aids and health insurance are instrumental in managing these expenses, aiding in broader accessibility of essential surgical treatments.
https://www.breastoncosurgery.com/services/breast-cancer-treatment-cost-in-delhi/

Great Things said...

Dr. Anjali Mehta is a renowned colorectal surgeon in Ahmedabad, bringing over 20 years of experience to her practice. She is affiliated with premier hospitals such as Zydus and CIMS, where she specializes in minimally invasive and robotic-assisted surgeries. Dr. Mehta’s patient-first philosophy ensures personalized care tailored to individual needs, promoting quicker recovery and better outcomes. Her commitment to ongoing education, through participating in global medical conferences, keeps her abreast of the latest advancements in colorectal surgery. Patients and colleagues alike commend her for clear communication and compassionate approach, making her a trusted choice for colorectal treatments in Ahmedabad.
https://drvirajlavingia.com/colorectal-cancer-specialist-in-ahmedabad

Rajeswari Vijayanand said...

Dr. Nisha Gupta is a distinguished oncology surgeon in Mumbai with over 20 years of specialized experience. She is highly proficient in advanced surgical techniques, including minimally invasive and robotic-assisted procedures. Dr. Gupta is affiliated with top-tier hospitals known for their state-of-the-art cancer care facilities. Her patient-centric approach focuses on providing personalized treatment plans tailored to meet each individual's unique medical needs. Dr. Gupta is renowned for her compassionate care and exemplary surgical outcomes, earning immense trust and respect from her patients and peers. She is committed to continuous education and integrating the latest medical advancements to ensure the highest standard of oncology care.
https://drnitanair.com/about/about-top-breast-cancer-surgeon-mumbai

twitch viral said...

Dr. Shona Nag is a renowned breast cancer specialist based in Pune, with over 22 years of clinical experience. She excels in traditional and advanced minimally invasive surgical techniques, ensuring excellent patient outcomes. Affiliated with leading hospitals, she provides access to cutting-edge medical technology. Dr. Nag is actively involved in pioneering research, keeping pace with the latest advancements in breast cancer treatment. Her patient-centric approach prioritizes empathy, personalized care, and comprehensive support throughout the treatment journey. Dr. Nag is highly respected by peers and patients alike for her commitment to improving patient prognosis and quality of life. She combines expertise, innovation, and compassionate care to deliver superior medical treatment.
https://www.drshonanagbreastcancer.in/understanding-cancer/what-is-cancer-can-cancer-be-cured

Travel Break said...

Ecommerce Website Design in Delhi specializes in crafting visually appealing and highly functional online stores tailored for businesses of all sizes. With a focus on user experience, these services incorporate intuitive navigation and attractive layouts to engage customers effectively. Essential features like secure payment gateways and real-time inventory management are integrated to ensure a seamless shopping experience. The designs are responsive, guaranteeing optimal display across various devices. Additionally, search engine optimization strategies are employed to enhance visibility and drive organic traffic. Customizable templates allow businesses to reflect their unique brand identity while meeting operational needs. Collaborative design processes involve working closely with clients to ensure their vision is realized. Ongoing support is provided to help businesses maintain and adapt their sites to the dynamic digital marketplace.
https://olycoder.com/ecommerce-website-design-delhi

Adventurous Kate said...

Minoxidil for men in Australia offers an effective remedy for addressing hair thinning and loss, actively stimulating hair follicle regrowth. Targeting common areas such as the crown and vertex, this topical solution is available in varying strengths to accommodate different levels of hair loss. Its clinically-validated formula ensures it delivers measurable results, enhancing hair density and thickness. Minoxidil's over-the-counter availability makes it easily accessible without a prescription, promoting user convenience. For optimal effectiveness, users must follow the application guidelines consistently. This treatment empowers men to improve hair vitality, boosting confidence with healthier hair.
https://generichealth.com.au/minoxidil-hair-loss/