@ ilavriv
struct Person {
first: &str,
last: &str
}
impl Person {
pub fn full(&self) -> String {
let full = self.first.to_string() + self.last;
return full.to_string();
}
}
fn main() {
let person = Person { first: "Ivan", last: "Lavriv" };
print!("Person: {}", person->full());
}Starting example
// simple initial varibles
let a = 1;
a = 2 // Error
// initial varible with type
let a : i32 = 1;
// init mutable varible
let mut a = 1;
a = 2;
Varibles
let a : i8 = 1;
let a : i16 = 1;
let a : i32 = 1;
let a : i64 = 1;
let b : f8 = 1.5;
let b : f16 = 1.5;
let b : f32 = 1.5;
let b : f64 = 6.5;
let c : u8 = 5;Algebraic types
//function synthax
fn factorial(&mut n : i32) -> uint {
match n {
0 => 1,
_ => factorial(n - 1),
}
}
// lambda function
let add_one = |&mut x : i32| x + 1;
// Higher order function Ex: #1
fn higher_order(func : fn (i32) -> i32) -> i32 {
return func();
}
// Higer order function Ex: #2
fn (x: i32) -> fn(i32) -> i32 { |x : i32| = x + 1 }
Functions
struct Point {
x : i32,
y : i32
}
let point = Point { x : 1, y : 1 };
print!("Point({} {})", point.x, point.y);Structures
use std::f64::consts::{FRAC_2_PI};
struct Circle {
radius : i32
}
impl Circle {
pub fn length(&self) -> f32 {
FRAC_2_PI * self.radius
}
}
Method synthax
use std::f64::consts::{PI};
trait Shape {
fn area(&self) -> f64;
}
struct Circle { radius: f64 }
struct Rectangle { length: f64, height: f64 }
impl Shape for Circle {
fn area(&self) -> f64 { PI * self.radius }
}
impl Shape for Rectangle {
fn area(&self) -> f64 { self.length * self.height }
}
Traits
mod A {
fn private_function() {}
pub fn public_function1() { // do something }
pub fn public_function2() { // do something }
pub public_module {
}
}
use A;
use A::public_module;
use A::public_module::{public_function1};
Modules
Methods
[package]
name = "test_addon"
version = "0.0.1"
authors = ["Ivan Lavriv <lavriv92gmail.com>"]
[lib]
name = "simple_addon"
crate_type = ["dylib"]
[dependencies]
# List of your dependensies
mongodb = "*"
// lib.rs
#[no_mangle]
fn public_function() {
// do something
}
# using_module.py
import ctypes
module = ctypes.cdll.LoadLibrary('./path_to_compiled_addon')
mudule.public_method()
use std::any::Any;
extern crate cpython;
use cpython::ObjectProtocol;
use cpython::{PyList, PyDict, PyObject, Python};
#[no_mangle]
fn get_data_as_dict() -> PyDict {}
#[no_mangle]
fn get_data_as_list(iterable: &[f64]) -> PyList {
let python = Python();
let result = iterable.map(|&elem: &T| {
match elem {
Some(elem) => process(elem),
None => Python.None()
}
});
return PyList(python, result);
}Fantasy world