Skip to content

Instantly share code, notes, and snippets.

@grahamking
grahamking / m2.rs
Created April 29, 2013 21:14
A module to use from a different file
pub fn say_hi() {
println("Hi!");
}
@grahamking
grahamking / objects.rs
Last active December 16, 2015 17:29
Rust: Objects
extern mod std;
use std::time;
struct User {
name: ~str,
age: int
}
impl User {
@grahamking
grahamking / mutable_pointers.rs
Last active December 16, 2015 17:29
Rust: The pointer and the box it points to
struct Point { x: int, y:int }
fn main() {
// Local variable, easy
let mut p1 = Point{x:1, y:2};
p1.x = 10;
// Owned pointer
// also easy because target inherts mutability
@grahamking
grahamking / memory_example.rs
Last active December 16, 2015 17:29
Rust: Owner memory example
fn main() {
let name: ~str,
other: ~str;
name = ~"Bob";
other = name;
println(other);
@grahamking
grahamking / use_sqlite.rs
Last active December 16, 2015 17:28
Rust: Use sqlite
extern mod sqlite;
fn db() {
let database =
match sqlite::open("test.db") {
Ok(db) => db,
Err(e) => {
println(fmt!("Error opening test.db: %?", e));
return;
@grahamking
grahamking / net_fetch.rs
Created April 26, 2013 19:43
Rust: Connect to a socket and talk
extern mod std;
use std::{net_tcp,net_ip};
use std::uv;
fn fetch(code: ~str) -> ~[~str] {
let ipaddr = net_ip::v4::parse_addr("205.156.51.232");
let iotask = uv::global_loop::get();
let connect_result = net_tcp::connect(ipaddr, 80, &iotask);
@grahamking
grahamking / load_file_2.rs
Created April 26, 2013 18:20
Rust: Load a file v2
fn load(filename: ~str) -> ~[~str] {
// The simple way:
// let read_result = io::file_reader(~path::Path(filename));
let read_result: Result<@Reader, ~str>;
read_result = io::file_reader(~path::Path(filename));
match read_result {
Ok(file) => return file.read_lines(),
@grahamking
grahamking / load_file.rs
Created April 26, 2013 17:42
Rust: Load a file
fn load(filename: ~str) -> ~[~str] {
// The simple way:
// let read_result = io::file_reader(~path::Path(filename));
let read_result: Result<@Reader, ~str>;
read_result = io::file_reader(~path::Path(filename));
if read_result.is_ok() {
let file = read_result.unwrap();
@grahamking
grahamking / loop.rs
Last active December 16, 2015 17:10
Rust: Loop three ways
fn main() {
for 2.times {
println("Basic loop sugar")
}
2.times(||{ println("Basic loop closure"); true });
for [1,2,3].each |var| {
println(fmt!("Sugary loop %d", *var));
}
@grahamking
grahamking / ask_name.rs
Last active December 16, 2015 17:09
Rust: Ask your name
/* Ask the user for their name */
fn ask_name(prompt: ~str) -> ~str {
println(prompt);
return io::stdin().read_line();
}
fn main() {
let name = ask_name(~"What is your name?");
println(fmt!("Hello %s", name));
}