Skip to content

Instantly share code, notes, and snippets.

View Norwae's full-sized avatar

Norwae

View GitHub Profile
@Norwae
Norwae / comod.java
Created August 25, 2020 07:16
CoMod
class ConcurrentModification {
public static void main(String[] args) {
var list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (var str : list) {
System.out.println("Doubling " + str);
list.add(str + str);
}
}
}
@Norwae
Norwae / lifetime.rs
Created August 25, 2020 07:05
Lifetime example
fn reference() -> u32 {
let x: u32 = 10;
let ref y = &x; // reference to x
let z: &u32;
{
let short_lived: u32 = 82;
z = &short_lived;
}
@Norwae
Norwae / destruction.rs
Last active August 21, 2020 14:57
Example showing destruction of objects
fn destruction() -> String{
let string1 = String::from("Hello World");
let string2 = String::new();
let string3 = string2; // string2 moved to string3, no longer valid
for i in 0..32 {
let another_string = String::from("Yellow Submarine");
do_something(another_string); // another_string "given away" here, no longer our concern
}
@Norwae
Norwae / matching.rs
Created August 21, 2020 13:20
Simple match example
fn match_it(x: Option<i32>, flag: bool) -> i32 {
match x {
None => 0,
Some(3) => 3,
Some(_) if !flag => 450,
Some(x) if x > 900 => 900,
_ => -1
}
}
@Norwae
Norwae / loops.rs
Created August 21, 2020 09:40
Loops in rust
fn loops(limit: u32, values: Vec<i32>, condition: bool) {
// while (condition)
while condition {
}
// for (var i: values)
for i in values {
}
@Norwae
Norwae / function.rs
Created August 21, 2020 09:09
simple_calc
fn calculate(x: i64, y: f64, z: i32) -> f64 {
let x = x + (if x < z as i64 { 2 } else { -5 });
let q = y * x;
q + z
}
@Norwae
Norwae / function.java
Created August 21, 2020 08:48
simple_calc
class Foo {
double calculate(long x, double y, int z) {
var delta = x < z ? 2 : -5;
x += delta;
var q = y * x;
return q + z;
}
}
@Norwae
Norwae / stringify.rs
Created August 21, 2020 08:35
Impl at trait
trait Stringify {
fn stringify(self) -> String;
}
impl Stringify for String {
fn stringify(self) -> String {
self
}
}
@Norwae
Norwae / basic_rust_struct.rs
Last active August 21, 2020 08:09
Simple Rust struct
pub struct Person {
name: String,
age: u32
}
impl Person {
pub fn new(name: String) -> Self {
Person { name, age: 18 }
}
}
@Norwae
Norwae / basic_java_class.java
Created August 21, 2020 07:57
Simple java class
public class Person implements Named {
private String name;
private int age;
public Person(String name) {
this.name = name;
this.age = 18;
}
@Override public String getName() {