Created
July 1, 2017 22:40
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
but don't use mutable things if you don't have to 🗡️