Rust vs Go:常用语法对比(2)

简介: Rust vs Go:常用语法对比(2)

11. Pick a random element from a list

从列表中选择一个随机元素

package main
import (
  "fmt"
  "math/rand"
)
var x = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}
func main() {
  fmt.Println(x[rand.Intn(len(x))])
}

输出

fuligin

or

package main
import (
  "fmt"
  "math/rand"
)
type T string
func pickT(x []T) T {
  return x[rand.Intn(len(x))]
}
func main() {
  var list = []T{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}
  fmt.Println(pickT(list))
}

输出

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);
}

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);
}

12. Check if list contains a value

Check if list contains a value x. list is an iterable finite container.

检查列表中是否包含一个值

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() {
  list := []T{"a", "b", "c"}
  fmt.Println(Contains(list, "b"))
  fmt.Println(Contains(list, "z"))
}

输出

true
false
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);
        }
    }
}

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);
    }
}

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);
    }
}

13. Iterate over map keys and values

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

遍历关联数组中的每一对 k-v, 并打印出它们

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

输出

Key = two , Value = 2
Key = three , Value = 3
Key = four , Value = 4
Key = one , Value = 1
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);
    }
}

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.

选出一个随机的浮点数,大于或等于a,严格小于b,且a< b

package main
import (
  "fmt"
  "math/rand"
)
func main() {
  x := pick(-2.0, 6.5)
  fmt.Println(x)
}
func pick(a, b float64) float64 {
  return a + (rand.Float64() * (b - a))
}

输出

3.1396124478267664

extern crate rand;
use rand::{thread_rng, Rng};
fn main() {
    let (a, b) = (1.0, 3.0);
    let c = thread_rng().gen_range(a..b);
    println!("{}", c);
}

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.

选出一个随机的整数,大于或等于a,小于或等于b,且a< b

package main
import (
  "fmt"
  "math/rand"
)
func main() {
  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)
}

输出

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)
}

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);
}

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.

创建树数据结构, 该结构必须是递归的。一个节点可以有零个或多个子节点,节点可以访问子节点,但不能访问其父节点

type Tree struct {
  Key keyType
  Deco valueType
  Children []*Tree
}
package main
import "fmt"
type Tree struct {
  Key      key
  Deco     value
  Children []*Tree
}
type key string
type value string
func (t *Tree) String() 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() {
  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)
}

输出

(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); });
}

输出:

50
28
14
80

18. Depth-first traversing of a tree

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

树的深度优先遍历。按照深度优先的前缀顺序,在树的每个节点上调用函数f

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() {
  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)
}

输出

Abraham (Granpa)
Homer (Dad)
Bart (Kid 1)
Lisa (Kid 2)
Maggie (Kid 3)
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); });
}

输出:

50
28
14
80

19. Reverse a list

Reverse the order of the elements of list x. This may reverse "in-place" and destroy the original ordering.

反转链表

package main
import "fmt"
func main() {
  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)
}

输出

[4 1 3 6 2 5]

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

输出:

["World", "Hello"]

or

fn main() {
    let mut x = vec![1,2,3];
    x.reverse();
    println!("{:?}", x);
}

输出:

[3, 2, 1]

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.

实现在2D矩阵m中寻找元素x,返回匹配单元格的索引 i,j

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() {
  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)
    }
  }
}

输出

matrix[0][0] == 1 
matrix[0][2] == 3 
matrix[1][1] == 5 
matrix[2][0] == 7 
matrix[2][2] == 9 
Value 11 not found. 
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);
}

输出:

Some((1, 1))
目录
相关文章
|
2天前
|
Rust 安全 编译器
30天拿下Rust之语法大全
Rust是一种系统级编程语言,以其独特的所有权系统和内存安全性受到开发者青睐。本文从基本数据类型入手,介绍了标量类型如整数、浮点数、布尔值及字符,复合类型如元组、数组和结构体等。此外,还探讨了变量与常量的声明与使用,条件判断与循环语句的语法,以及函数定义与调用的方法。文章通过示例代码展示了如何使用Rust编写简洁高效的程序,并简要介绍了注释与宏的概念,为读者快速掌握这门语言提供了实用指南。欲获取最新文章或交流技术问题,请关注微信公众号“希望睿智”。
|
2月前
|
存储 Java Go
|
1月前
|
Rust
Rust 中使用 :: 这种语法的几种情况
Rust 中使用 :: 这种语法的几种情况
|
2月前
|
Rust
Rust的if let语法:更简洁的模式匹配
Rust的if let语法:更简洁的模式匹配
9 0
|
2月前
|
编译器 Go 开发者
|
2月前
|
Go
go基础语法结束篇 ——函数与方法
go基础语法结束篇 ——函数与方法
|
2月前
|
编译器 Go 数据安全/隐私保护
go语言入门之路——基础语法
go语言入门之路——基础语法
|
2月前
|
存储 安全 Java
【Go语言精进之路】Go语言基础:基础语法概览
【Go语言精进之路】Go语言基础:基础语法概览
34 0
|
2月前
|
Java Go Scala
|
2月前
|
存储 Java Unix