Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

The snippets are under the CC-BY-SA license.

Programming-Idioms.org
Creative Commons Attribution-ShareAlike 3.0

Go Rust
1 Print Hello World
Print a literal string on fmt.Println("Hello World") println!("Hello World");
standard output
2 Print Hello 10 times
Loop to execute some for i := 0; i < 10; i++ { for _ in 0..10 { println!("Hello"); }
code a constant number fmt.Println("Hello")
of times
}
Alternative implementation:
print!("{}", "Hello\n".repeat(10));
Alternative implementation:
fmt.Println(strings.Repeat("Hello\n", 1
0))

3 Create a procedure
Like a function which func finish(name string) { fn finish(name: &str) {
doesn't return any value,
fmt.Println("My job here is done. Goo println!("My job here is done. Good
thus has only side
d bye " + name) bye {}", name);
effects (e.g. Print to } }
standard output)
Alternative implementation:

finish := func(name string) {


fmt.Println("My job here is don
e. Good bye " + name)
}

4 Create a function
func square(x int) int { fn square(x : u32) -> u32 { x * x }
Create a function which
return x*x
returns the square of an
}
integer

5 Create a 2D Point data


structure
type Point struct { struct Point {
Declare a container type
x, y float64 x: f64,
for two floating-point
} y: f64,
numbers x and y
}

Alternative implementation:

struct Point(f64, f64);

6 Iterate over list values


Do something with each
for _, x := range items { for x in items {
item x of the list (or
doSomething(x) do_something(x);
array) items, regardless
} }
indexes.
Alternative implementation:

items.into_iter().for_each(|x| do_somet
hing(x));

7 Iterate over list indexes


and values for i, x := range items { for (i, x) in items.iter().enumerate()
Print each index i with its
fmt.Printf("Item %d = %v \n", i, x) {
value x from an array-
} println!("Item {} = {}", i, x);
like collection items
}

Alternative implementation:

items.iter().enumerate().for_each(|(i,
x)| {
println!("Item {} = {}", i, x);
})

You might also like