1. Print Hello World

Prints Hello World

package main

import "fmt"


func main(a) {
	fmt.Println("Hello World")}Copy the code

fn main() {
    println!("Hello World");
}

Copy the code

Rust outputs text in two main ways: println! () and print! (). Both of these “functions” are methods that print strings to the command line, the only difference being that the former appends a newline at the end of the output. When using these two “functions” to output information, the first argument is the format string, followed by a string of variators that correspond to the “placeholders” in the format string, similar to the printf function in C/Go. However, the placeholders in Rust’s format string are not of the form “% + letters “, but a pair of {}.


2. Print Hello 10 times

Print Hello World 10 times

package main

import (
	"fmt"
)

func main(a) {
	for i := 0; i < 10; i++ {
		fmt.Println("Hello")}}Copy the code

fn main() {
    for _ in 0.10 {
        println!("Hello"); }}Copy the code

or

fn main() {
    print!("{}"."Hello\n".repeat(10));
}

Copy the code


3. Create a procedure

Like a function which doesn’t return any value, thus has only side effects (e.g. Print to standard output)

Create a method that returns no value and prints something

package main

import "fmt"

func finish(name string) {
	fmt.Println("My job here is done. Good bye " + name)
}

func main(a) {
	finish("Tony")}Copy the code

fn main(){
    finish("Buddy")}fn finish(name : &str) {
    println!("My job here is done. Goodbye {}", name);
}
Copy the code


4. Create a function which returns the square of an integer

Creates a function that returns the square of an integer

func square(x int) int {
  return x*x
}

Copy the code

fn square(x: u32) - >u32 {
    x * x
}

fn main() {
    let sq = square(9);

    println!("{}", sq);
}

Copy the code


5. Create a 2D Point data structure

Declare a container type for two floating-point numbers x and y

Declare a container type with two floating point numbers x and y

package main

import "fmt"

type Point struct {
	x, y float64
}

func main(a) {
	p1 := Point{}
	p2 := Point{2.1.2.2}
	p3 := Point{
		y: 3.1,
		x: 3.2,
	}
	p4 := &Point{
		x: 4.1,
		y: 4.2,
	}

	fmt.Println(p1)
	fmt.Println(p2)
	fmt.Println(p3)
	fmt.Println(p4)
}

Copy the code

The output

{0 0}
{2.1 2.2}
{3.2 3.1} and {4.1 4.2}

Copy the code

use std::fmt;

struct Point {
    x: f64,
    y: f64,}impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})".self.x, self.y)
    }
}

fn main() {
    let p = Point { x: 2.0, y: -3.5 };

    println!("{}", p);
}
Copy the code

or

use std::fmt;

struct Point(f64.f64);

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})".self.0.self.1)}}fn main() {
    let p = Point(2.0, -3.5);

    println!("{}", p);
}

Copy the code


6. Iterate over list values

Do something with each item x of an array-like collection items, regardless indexes.

Iterate over the values of the list

for _, x := range items {
    doSomething(x)
}

Copy the code
package main

import (
	"fmt"
)

func main(a) {
	items := []int{11.22.33}

	for _, x := range items {
		doSomething(x)
	}
}

func doSomething(i int) {
	fmt.Println(i)
}
Copy the code

The output

11
22
33
Copy the code

fn main() {
    let items = vec![11.22.33];

    for x initems { do_something(x); }}fn do_something(n: i64) {
    println!("Number {}", n)
}
Copy the code

or

fn main() {
    let items = vec![11.22.33];

    items.into_iter().for_each(|x| do_something(x));
}

fn do_something(n: i64) {
    println!("Number {}", n)
}
Copy the code


7. Iterate over list indexes and values

Iterate over the indexes and values of the list

package main

import "fmt"

func main(a) {
	items := []string{
		"oranges"."apples"."bananas",}for i, x := range items {
		fmt.Printf("Item %d = %v \n", i, x)
	}
}

Copy the code

The output

Item 0 = oranges 
Item 1 = apples 
Item 2 = bananas 
Copy the code

fn main() {
    let items = ["a"."b"."c"];
    for (i, x) in items.iter().enumerate() {
        println!("Item {} = {}", i, x); }}Copy the code

or

fn main() {
    let items = ["a"."b"."c"];
    items.iter().enumerate().for_each(|(i, x)| {
        println!("Item {} = {}", i, x);
    });
}
Copy the code


8. Initialize a new map (associative array)

Create a new map object x, and provide some (key, value) pairs as initial content.

Create a new map, providing some key-value pairs as the initial content

package main

import "fmt"

func main(a) {
	x := map[string]int{"one": 1."two": 2}

	fmt.Println(x)
}

Copy the code

The output

map[one:1 two:2]
Copy the code

use std::collections::BTreeMap;

fn main() {
    let mut x = BTreeMap::new();
    x.insert("one".1);
    x.insert("two".2);
    
    println!("{:? }", x);
}
Copy the code

The output is:

("one".1)
("two".2)
Copy the code

or

use std::collections::HashMap;

fn main() {
    let x: HashMap<&str.i32> = [("one".1),
        ("two".2),
    ].iter().cloned().collect();
    
    println!("{:? }", x);
}
Copy the code

The output is:

("two".2)
("one".1)
Copy the code

There are BTreeMap and HashMap, and both require use


9. Create a Binary Tree data structure

The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.

Create a binary tree

type BinTree struct {
	Value valueType
	Left *BinTree
	Right *BinTree
}
Copy the code
package main

import "fmt"

type BinTree struct {
	Value int
	Left  *BinTree
	Right *BinTree
}

func inorder(root *BinTree) {
	if root == nil {
		return
	}

	inorder(root.Left)
	fmt.Printf("%d ", root.Value)
	inorder(root.Right)
}

func main(a) {
	root := &BinTree{1.nil.nil}
	root.Left = &BinTree{2.nil.nil}
	root.Right = &BinTree{3.nil.nil}
	root.Left.Left = &BinTree{4.nil.nil}
	root.Left.Right = &BinTree{5.nil.nil}
	root.Right.Right = &BinTree{6.nil.nil}
	root.Left.Left.Left = &BinTree{7.nil.nil}

	inorder(root)
}
Copy the code

The output

7 4 2 5 1 3 6 
Copy the code

struct BinTree<T> {
    value: T,
    left: Option<Box<BinTree<T>>>,
    right: Option<Box<BinTree<T>>>,
}

Copy the code


10. Shuffle a list

Generate a random permutation of the elements of list x

Sort a list randomly

go

package main

import (
	"fmt"
	"math/rand"
)

func main(a) {
	x := []string{"a"."b"."c"."d"."e"."f"."g"."h"}

	for i := range x {
		j := rand.Intn(i + 1)
		x[i], x[j] = x[j], x[i]
	}

	fmt.Println(x)
}

Copy the code

The output

[f e c g h a d b]

or

package main

import (
	"fmt"
	"math/rand"
)

func main(a) {
	x := []string{"a"."b"."c"."d"."e"."f"."g"."h"}

	y := make([]string.len(x))
	perm := rand.Perm(len(x))
	for i, v := range perm {
		y[v] = x[i]
	}

	fmt.Println(y)
}
Copy the code

The output

[f h c g b a d e]

or

package main

import (
	"fmt"
	"math/rand"
)

func main(a) {
	x := []string{"a"."b"."c"."d"."e"."f"."g"."h"}

	y := make([]string.len(x))
	perm := rand.Perm(len(x))
	for i, v := range perm {
		y[v] = x[i]
	}

	fmt.Println(y)
}

Copy the code

The output

[f h c g b a d e]

or

package main

import (
	"fmt"
	"math/rand"
)

func main(a) {
	x := []string{"a"."b"."c"."d"."e"."f"."g"."h"}

	for i := len(x) - 1; i > 0; i-- {
		j := rand.Intn(i + 1)
		x[i], x[j] = x[j], x[i]
	}

	fmt.Println(x)
}
Copy the code

The output

[g d a h e f c b]


extern crate rand;
use rand::{Rng, StdRng};

let mut rng = StdRng::new().unwrap();
rng.shuffle(&mut x);
Copy the code

or

use rand::seq::SliceRandom;
use rand::thread_rng;

fn main() {
    let mut x = [1.2.3.4.5];
    println!("Unshuffled: {:? }", x);

    let mut rng = thread_rng();
    x.shuffle(&mut rng);

    println!("Shuffled: {:? }", x);
}

Copy the code


11. Pick a random element from a list

Select a random element from the list

package main

import (
	"fmt"
	"math/rand"
)

var x = []string{"bleen"."fuligin"."garrow"."grue"."hooloovoo"}

func main(a) {
	fmt.Println(x[rand.Intn(len(x))])
}

Copy the code

The output

fuligin

or

package main

import (
	"fmt"
	"math/rand"
)

type T string

func pickT(x []T) T {
	return x[rand.Intn(len(x))]
}

func main(a) {
	var list = []T{"bleen"."fuligin"."garrow"."grue"."hooloovoo"}
	fmt.Println(pickT(list))
}

Copy the code

The output

fuligin


use rand::{self, Rng};

fn main() {
    let x = vec![11.22.33];

    let choice = x[rand::thread_rng().gen_range(0..x.len())];

    println!("I picked {}!", choice);
}
Copy the code

or

use rand::seq::SliceRandom;
 
fn main() {
    let x = vec![11.22.33];

    let mut rng = rand::thread_rng();
    let choice = x.choose(&mut rng).unwrap();
    
    println!("I picked {}!", choice);
}
Copy the code


12. Check if list contains a value

Check if list contains a value x.

list is an iterable finite container.

Check if the list contains a value

package main

import "fmt"

func Contains(list []T, x T) bool {
	for _, item := range list {
		if item == x {
			return true}}return false
}

type T string

func main(a) {
	list := []T{"a"."b"."c"}
	fmt.Println(Contains(list, "b"))
	fmt.Println(Contains(list, "z"))}Copy the code

The output

true
false
Copy the code

fn main() {
    let list = [10.40.30];

    {
        let num = 30;

        if list.contains(&num) {
            println!("{:? } contains {}", list, num);
        } else {
            println!("{:? } doesn't contain {}", list, num); }} {let num = 42;

        if list.contains(&num) {
            println!("{:? } contains {}", list, num);
        } else {
            println!("{:? } doesn't contain {}", list, num); }}}Copy the code

or

fn main() {
    let list = [10.40.30];
    let x = 30;

    if list.iter().any(|v| v == &x) {
        println!("{:? } contains {}", list, x);
    } else {
        println!("{:? } doesn't contain {}", list, x); }}Copy the code

or

fn main() {
    let list = [10.40.30];
    let x = 30;

    if (&list).into_iter().any(|v| v == &x) {
        println!("{:? } contains {}", list, x);
    } else {
        println!("{:? } doesn't contain {}", list, x); }}Copy the code


13. Iterate over map keys and values

Access each key k with its value x from an associative array mymap, and print them

Iterates over each pair of K-Vs in the associative array and prints them out

package main

import "fmt"

func main(a) {
	mymap := map[string]int{
		"one":   1."two":   2."three": 3."four":  4,}for k, x := range mymap {
		fmt.Println("Key =", k, ", Value =", x)
	}
}
Copy the code

The output

Key = two , Value = 2
Key = three , Value = 3
Key = four , Value = 4
Key = one , Value = 1
Copy the code

use std::collections::BTreeMap;

fn main() {
    let mut mymap = BTreeMap::new();
    mymap.insert("one".1);
    mymap.insert("two".2);
    mymap.insert("three".3);
    mymap.insert("four".4);

    for (k, x) in &mymap {
        println!("Key={key}, Value={val}", key = k, val = x); }}Copy the code


14. Pick uniformly a random floating point number in [a..b)

Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.

Pick a random floating point number, greater than or equal to a, strictly less than b, and a< b

package main

import (
	"fmt"
	"math/rand"
)

func main(a) {
	x := pick(2.0.6.5)
	fmt.Println(x)
}

func pick(a, b float64) float64 {
	return a + (rand.Float64() * (b - a))
}
Copy the code

The output

3.1396124478267664


extern crate rand;
use rand::{thread_rng, Rng};

fn main() {
    let (a, b) = (1.0.3.0);
    letc = thread_rng().gen_range(a.. b);println!("{}", c);
}
Copy the code


15. Pick uniformly a random integer in [a..b]

Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.

Pick a random integer, greater than or equal to a, less than or equal to b, and a less than b

package main

import (
	"fmt"
	"math/rand"
)

func main(a) {
	x := pick(3.7)

	// Note that in the Go Playground, time and random don't change very often.
	fmt.Println(x)
}

func pick(a, b int) int {
	return a + rand.Intn(b-a+1)}Copy the code

The output

4


fn pick(a: i32, b: i32) - >i32 {
    let between = Range::new(a, b);
    let mut rng = rand::thread_rng();
    between.ind_sample(&mut rng)
}
Copy the code

or

use rand::distributions::Distribution;
use rand::distributions::Uniform;

fn main() {
    let (a, b) = (3.5);

    let x = Uniform::new_inclusive(a, b).sample(&mut rand::thread_rng());

    println!("{}", x);
}
Copy the code


17. Create a Tree data structure

The structure must be recursive. A node may have zero or more children. A node has access to children nodes, but not to its parent.

Create a tree data structure, which must be recursive. A node can have zero or more children. A node can access its children, but not its parents

type Tree struct {
	Key keyType
	Deco valueType
	Children []*Tree
}
Copy the code
package main

import "fmt"

type Tree struct {
	Key      key
	Deco     value
	Children []*Tree
}

type key string
type value string

func (t *Tree) String(a) string {
	str := "("
	str += string(t.Deco)
	if len(t.Children) == 0 {
		return str + ")"
	}
	str += "("
	for _, child := range t.Children {
		str += child.String()
	}
	str += ")"
	return str
}

func (this *Tree) AddChild(x key, v value) *Tree {
	child := &Tree{Key: x, Deco: v}
	this.Children = append(this.Children, child)
	return child
}

func main(a) {
	tree := &Tree{Key: "Granpa", Deco: "Abraham"}
	subtree := tree.AddChild("Dad"."Homer")
	subtree.AddChild("Kid 1"."Bart")
	subtree.AddChild("Kid 2"."Lisa")
	subtree.AddChild("Kid 3"."Maggie")

	fmt.Println(tree)
}

Copy the code

The output

(Abraham ((Homer ((Bart)(Lisa)(Maggie)))))


use std::vec;

struct Node<T> {
    value: T,
    children: Vec<Node<T>>,
}

impl<T> Node<T> {
    pub fn dfs<F: Fn(&T)>(&self, f: F) {
       self.dfs_helper(&f);
    }

    fn dfs_helper<F: Fn(&T)>(&self, f: &F) {
        (f)(&self.value);
        for child in &self.children { child.dfs_helper(f); }}}fn main() {
    let t: Node<i32> = Node {
        children: vec![
            Node {
                children: vec![
                    Node {
                        children: vec![],
                        value: 14
                    }
                ],
                value: 28
            },
            Node {
                children: vec![],
                value: 80
            }
        ],
        value: 50
    };

    t.dfs(|node| { println!("{}", node); });
}
Copy the code

Output:

50
28
14
80
Copy the code


18. Depth-first traversing of a tree

Call a function f on every node of a tree, in depth-first prefix order

Depth-first traversal of the tree. The function f is called on each node of the tree in depth-first prefix order

package main

import . "fmt"

func (t *Tree) Dfs(f func(*Tree)) {
	if t == nil {
		return
	}
	f(t)
	for _, child := range t.Children {
		child.Dfs(f)
	}
}

type key string
type value string

type Tree struct {
	Key      key
	Deco     value
	Children []*Tree
}

func (this *Tree) AddChild(x key, v value) {
	child := &Tree{Key: x, Deco: v}
	this.Children = append(this.Children, child)
}

func NodePrint(node *Tree) {
	Printf("%v (%v)\n", node.Deco, node.Key)
}

func main(a) {
	tree := &Tree{Key: "Granpa", Deco: "Abraham"}
	tree.AddChild("Dad"."Homer")
	tree.Children[0].AddChild("Kid 1"."Bart")
	tree.Children[0].AddChild("Kid 2"."Lisa")
	tree.Children[0].AddChild("Kid 3"."Maggie")

	tree.Dfs(NodePrint)
}

Copy the code

The output

Abraham (Granpa)
Homer (Dad)
Bart (Kid 1)
Lisa (Kid 2)
Maggie (Kid 3)
Copy the code

use std::vec;

struct Tree<T> {
    children: Vec<Tree<T>>,
    value: T
}

impl<T> Tree<T> {
    pub fn new(value: T) -> Self{
        Tree{
            children: vec![],
            value
        }
    }

    pub fn dfs<F: Fn(&T)>(&self, f: F) {
       self.dfs_helper(&f);
    }

    fn dfs_helper<F: Fn(&T)>(&self, f: &F) {
        (f)(&self.value);
        for child in &self.children { child.dfs_helper(f); }}}fn main() {
    let t: Tree<i32> = Tree {
        children: vec![
            Tree {
                children: vec![
                    Tree {
                        children: vec![],
                        value: 14
                    }
                ],
                value: 28
            },
            Tree {
                children: vec![],
                value: 80
            }
        ],
        value: 50
    };

    t.dfs(|node| { println!("{}", node); });
}
Copy the code

Output:

50
28
14
80
Copy the code


19. Reverse a list

Reverse the order of the elements of list x.

This may reverse “in-place” and destroy the original ordering.

Reverse a linked list

package main

import "fmt"

func main(a) {

	s := []int{5.2.6.3.1.4}

	for i, j := 0.len(s)- 1; i < j; i, j = i+1, j- 1 {
		s[i], s[j] = s[j], s[i]
	}

	fmt.Println(s)
}

Copy the code

The output

[4]


fn main() {
    let x = vec!["Hello"."World"];
    let y: Vec<_> = x.iter().rev().collect();
    println!("{:? }", y);
}
Copy the code

Output:

["World"."Hello"]
Copy the code

or

fn main() {
    let mut x = vec![1.2.3];
    x.reverse();
    println!("{:? }", x);
}
Copy the code

Output:

[3.2.1]
Copy the code


20. Return two values

Implement a function search which looks for item x in a 2D matrix m.

Return indices i, j of the matching cell. Think of the most idiomatic way in the language to return the two values at the same time.

To find the element x in the 2D matrix m, return the index I, j of the matching cell

package main

import "fmt"

func search(m [][]int, x int) (bool.int.int) {
	for i := range m {
		for j, v := range m[i] {
			if v == x {
				return true, i, j
			}
		}
	}
	return false.0.0
}

func main(a) {
	matrix := [][]int{{1.2.3},
		{4.5.6},
		{7.8.9}},for x := 1; x <= 11; x += 2 {
		found, i, j := search(matrix, x)
		if found {
			fmt.Printf("matrix[%v][%v] == %v \n", i, j, x)
		} else {
			fmt.Printf("Value %v not found. \n", x)
		}
	}
}
Copy the code

The output

matrix[0] [0] = =1 
matrix[0] [2] = =3 
matrix[1] [1] = =5 
matrix[2] [0] = =7 
matrix[2] [2] = =9 
Value 11 not found. 
Copy the code

fn search<T: Eq>(m: &Vec<Vec<T>>, x: &T) -> Option< (usize.usize) > {for (i, row) in m.iter().enumerate() {
        for (j, column) in row.iter().enumerate() {
            if *column == *x {
                return Some((i, j)); }}}None
}

fn main() {
    let a = vec![
        vec![0.11].vec![22.33].vec![44.55]];let hit = search(&a, &33);
    
    println!("{:? }", hit);
}
Copy the code

Output:

Some((1.1))
Copy the code