Skip to content

Instantly share code, notes, and snippets.

@HIMISOCOOL
Created July 1, 2017 22:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HIMISOCOOL/fe02fc1030fbc55f0d07376faba12d6d to your computer and use it in GitHub Desktop.
Save HIMISOCOOL/fe02fc1030fbc55f0d07376faba12d6d to your computer and use it in GitHub Desktop.
Rust doesnt have inheritance but that doesnt mean you cant do the same things
struct Waterway {
name: &'static str
}
trait WaterwayTrait {
fn get_name(&self) -> &'static str;
fn set_name(&mut self, value: &'static str);
}
struct Sea {
waterway: Waterway,
// important to note that while these are in the same file there is no scoping
// if these structs were in a different module they would all be private by default
pub area: f32
}
impl Sea {
fn new(name: &'static str, area: f32) -> Sea {
let waterway = Waterway { name: name };
// remembering that a statement with no semicolon is 'return'
Sea { waterway, area}
}
}
impl WaterwayTrait for Sea {
fn get_name(&self) -> &'static str {
self.waterway.name
}
fn set_name(&mut self, value: &'static str) {
self.waterway.name = value;
}
}
fn main() {
let mut dead_sea = Sea::new("Dead Sea", 602.0);
println!("This is the {}. It is {} Km^2", dead_sea.get_name(), dead_sea.area);
dead_sea.set_name("Deadly Sea");
println!("This is the {}. It is {} Km^2", dead_sea.get_name(), dead_sea.area);
}
using System;
namespace HelloWorld
{
abstract class Waterway
{
internal string name;
}
class Sea : Waterway
{
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public Double Area;
public Sea(string name, double area)
{
this.name = name;
this.Area = area;
}
}
class Program
{
static void Main(string[] args)
{
var deadSea = new Sea("Dead Sea", 602.0);
Console.WriteLine("This is the {0}. It is {1} Km^2", deadSea.Name, deadSea.Area);
deadSea.Name = "Deadly Sea";
Console.WriteLine("This is the {0}. It is {1} Km^2", deadSea.Name, deadSea.Area)
}
}
}
@HIMISOCOOL
Copy link
Author

but don't use mutable things if you don't have to 🗡️

trait WaterwayTrait {
    fn get_name(&self) -> &'static str;
    fn set_name(&self, value: &'static str) -> Sea;
}

impl WaterwayTrait for Sea {
    fn get_name(&self) -> &'static str {
        self.waterway.name
    }
    fn set_name(&self, value: &'static str) -> Sea {
        Sea::new(value, self.area)
    }
}

fn main() {
    let dead_sea = Sea::new("Dead Sea", 602.0);
    println!("This is the {}. It is {} Km^2", dead_sea.get_name(), dead_sea.area);
    let deadly_sea = dead_sea.set_name("Deadly Sea");
    println!("This is the {}. It is {} Km^2", deadly_sea.get_name(), deadly_sea.area);
}

@flyingllama87
Copy link

Nice example.

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