Skip to content

Instantly share code, notes, and snippets.

@barseghyanartur
Created February 15, 2023 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barseghyanartur/0efb2b10aab094bbcef30bfdd037dbeb to your computer and use it in GitHub Desktop.
Save barseghyanartur/0efb2b10aab094bbcef30bfdd037dbeb to your computer and use it in GitHub Desktop.
Project structure in Rust

Project structure in Rust

Tree

├── Cargo.toml
└── src
    ├── lib.rs
    ├── main.rs
    └── traits.rs

Sources

src/lib.rs

pub mod traits;

pub use self::traits::Summary;

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

src/main.rs

use aggregator::{Summary, Tweet};

fn main() {
    let tweet = Tweet {
        username: String::from("horse_ebooks"),
        content: String::from(
            "of course, as you probably already know, people",
        ),
        reply: false,
        retweet: false,
    };

    println!("1 new tweet: {}", tweet.summarize());
}

src/traits.rs

pub trait Summary {
    fn summarize(&self) -> String;
}

Cargo.toml

[package]
name = "aggregator"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment