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

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

image.png


1. Print Hello World


打印Hello World

package main
import "fmt"
func main() {
  fmt.Println("Hello World")
}
fn main() {
    println!("Hello World");
}

Rust 输出文字的方式主要有两种:println!()print!()。这两个"函数"都是向命令行输出字符串的方法,区别仅在于前者会在输出的最后附加输出一个换行符。当用这两个"函数"输出信息的时候,第一个参数是格式字符串,后面是一串可变参数,对应着格式字符串中的"占位符",这一点与 C 语言/ Go语言 中的 printf 函数很相似。但是,Rust 中格式字符串中的占位符不是"% + 字母"的形式,而是一对 {}。


2. Print Hello 10 times


打印10次Hello World

package main
import (
  "fmt"
)
func main() {
  for i := 0; i < 10; i++ {
    fmt.Println("Hello")
  }
}
fn main() {
    for _ in 0..10 {
        println!("Hello");
    }
}

or

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


3. Create a procedure


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

创建一个方法,没有返回值,打印一些内容

package main
import "fmt"
func finish(name string) {
  fmt.Println("My job here is done. Good bye " + name)
}
func main() {
  finish("Tony")
}
fn main(){
    finish("Buddy")
}
fn finish(name : &str) {
    println!("My job here is done. Goodbye {}", name);
}


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


创建一个函数,返回一个整数的平方

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


fn square(x: u32) -> u32 {
    x * x
}
fn main() {
    let sq = square(9);
    println!("{}", sq);
}


5. Create a 2D Point data structure


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

声明一个容器类型,有x、y两个浮点数

package main
import "fmt"
type Point struct {
  x, y float64
}
func main() {
  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)
}

输出

{0 0}
{2.1 2.2}
{3.2 3.1}
&{4.1 4.2}
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);
}

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


6. Iterate over list values


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

遍历列表的值

for _, x := range items {
    doSomething(x)
}
package main
import (
  "fmt"
)
func main() {
  items := []int{11, 22, 33}
  for _, x := range items {
    doSomething(x)
  }
}
func doSomething(i int) {
  fmt.Println(i)
}

输出

11
22
33
fn main() {
    let items = vec![11, 22, 33];
    for x in items {
        do_something(x);
    }
}
fn do_something(n: i64) {
    println!("Number {}", n)
}

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


7. Iterate over list indexes and values


遍历列表的索引和值

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

输出

Item 0 = oranges 
Item 1 = apples 
Item 2 = bananas 


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

or

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


8. Initialize a new map (associative array)


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

创建一个新的map,提供一些键值对 作为初始内容权,非商业转载请注明出处。

package main
import "fmt"
func main() {
  x := map[string]int{"one": 1, "two": 2}
  fmt.Println(x)
}

输出

map[one:1 two:2]
use std::collections::BTreeMap;
fn main() {
    let mut x = BTreeMap::new();
    x.insert("one", 1);
    x.insert("two", 2);
    println!("{:?}", x);
}

输出为:

("one", 1)
("two", 2)

or

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

输出为

("two", 2)
("one", 1)

分 BTreeMap 和 HashMap,且都需要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.

创建一个二叉树

type BinTree struct {
  Value valueType
  Left *BinTree
  Right *BinTree
}
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() {
  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)
}

输出

7 4 2 5 1 3 6 
struct BinTree<T> {
    value: T,
    left: Option<Box<BinTree<T>>>,
    right: Option<Box<BinTree<T>>>,
}


10. Shuffle a list


Generate a random permutation of the elements of list x

随机排序一个list

目录
相关文章
|
17天前
|
Rust API
【Rust学习】09_方法语法
结构体让你可以创建出在你的领域中有意义的自定义类型。通过结构体,我们可以将相关联的数据片段联系起来并命名它们,这样可以使得代码更加清晰。在 impl 块中,你可以定义与你的类型相关联的函数,而方法是一种相关联的函数,允许您指定结构体的实例具有的行为。 但是结构体并不是创建自定义类型的唯一方式:让我们转向 Rust 的 enum 功能,将另一个工具添加到你的工具箱中。
10 0
|
28天前
|
Java 编译器 Go
Go to Learn Go之基础语法
Go to Learn Go之基础语法
16 0
|
2月前
|
Rust 安全 编译器
30天拿下Rust之语法大全
Rust是一种系统级编程语言,以其独特的所有权系统和内存安全性受到开发者青睐。本文从基本数据类型入手,介绍了标量类型如整数、浮点数、布尔值及字符,复合类型如元组、数组和结构体等。此外,还探讨了变量与常量的声明与使用,条件判断与循环语句的语法,以及函数定义与调用的方法。文章通过示例代码展示了如何使用Rust编写简洁高效的程序,并简要介绍了注释与宏的概念,为读者快速掌握这门语言提供了实用指南。欲获取最新文章或交流技术问题,请关注微信公众号“希望睿智”。
39 1
|
1月前
|
Rust Linux Go
Rust/Go语言学习
Rust/Go语言学习
|
4月前
|
存储 Java Go
|
3月前
|
Rust
Rust 中使用 :: 这种语法的几种情况
Rust 中使用 :: 这种语法的几种情况
|
4月前
|
Rust
Rust的if let语法:更简洁的模式匹配
Rust的if let语法:更简洁的模式匹配
|
4月前
|
编译器 Go 开发者
|
4月前
|
Go
go基础语法结束篇 ——函数与方法
go基础语法结束篇 ——函数与方法
|
4月前
|
编译器 Go 数据安全/隐私保护
go语言入门之路——基础语法
go语言入门之路——基础语法