Skip to content

Instantly share code, notes, and snippets.

@matthewphilyaw
Created March 18, 2014 17:02
Show Gist options
  • Save matthewphilyaw/9624442 to your computer and use it in GitHub Desktop.
Save matthewphilyaw/9624442 to your computer and use it in GitHub Desktop.
// these two are taken from the docs
struct Point {
x: f64,
y: f64
}
// They use shape later in the docs to show pattern matching
// but I'm going to attempt to explain it
// In the parens you are declaring list of types that variant makes
// up essentially. So Circle defines a Point (center), Float (Radius)
// Rectange is Point (top left) and Point (bottom right)
enum Shape {
Circle(Point, f64),
Rectangle(Point, Point)
}
// Now lets say we do this
let a: Shape = Circle(Point { x: 12, y: 10}, 6.0);
let b: Shape = Rectange(Point { x: 5, y: 5 }, Point { x: 10, y: 10 });
// match detructures shape so you can use the value
// also notice how the variables are pulled out of it as well.
fn area(s: Shape) {
match s {
Circle(c, r) => ...,
Rectangle(tr, bl) => ...
}
}
/*
as a side not the { } operator is interesting it's an expression and the last thing
evaluated without a semicolon is the return value if a the satement has a semicolon
then the expression returns the unit value of ()
so
{
let x = 4;
x
}
returns 4
where as
{
let x = 4;
x;
}
returns ()
there is a return statement but is generally considered bad practice to use (per docs) unless
you are trying to exit early.
/*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment