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

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

21. Swap values

交换变量a和b的值

a, b = b, a
package main
import "fmt"
func main() {
  a := 3
  b := 10
  a, b = b, a
  fmt.Println(a)
  fmt.Println(b)
}
10
3
fn main() {
    let a = 3;
    let b = 10;
    let (a, b) = (b, a);
    println!("a: {a}, b: {b}", a=a, b=b);
}

输出

a: 10, b: 3

or

fn main() {
    let (a, b) = (12, 42);
    println!("a = {}, b = {}", a, b);
    let (a, b) = (b, a);
    println!("a = {}, b = {}", a, b);
}

输出

a = 12, b = 42
a = 42, b = 12

22. Convert string to integer

将字符串转换为整型

import "strconv"
i, err  := strconv.Atoi(s) 
package main
import (
  "fmt"
  "reflect"
  "strconv"
)
func main() {
  // create a string
  s := "123"
  fmt.Println(s)
  fmt.Println("type:", reflect.TypeOf(s))
  // convert string to int
  i, err := strconv.Atoi(s)
  if err != nil {
    panic(err)
  }
  fmt.Println(i)
  fmt.Println("type:", reflect.TypeOf(i))
}
123
type: string
123
type: int

or

import "strconv"
i, err := strconv.ParseInt(s, 10, 0)
package main
import (
  "fmt"
  "reflect"
  "strconv"
)
func main() {
  s := "123"
  fmt.Println("s is", reflect.TypeOf(s), s)
  i, err := strconv.ParseInt(s, 10, 0)
  if err != nil {
    panic(err)
  }
  fmt.Println("i is", reflect.TypeOf(i), i)
}
s is string 123
i is int64 123
fn main() {
    // This prints 123
    let mut s = "123";
    let mut i = s.parse::<i32>().unwrap();
    println!("{:?}", i);
    // This panics
    s = "12u3";
    i = s.parse::<i32>().unwrap();
    println!("{:?}", i);
}

输出

123
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:860
note: Run with `RUST_BACKTRACE=1` for a backtrace.

or

fn main() {
    let mut s = "123";
    let mut i: i32 = s.parse().unwrap_or(0);
    println!("{:?}", i);
    s = "12u3";
    i = s.parse().unwrap_or(0);
    println!("{:?}", i);
}

输出

123
0

or

fn main() {
    let mut s = "123";
    let mut i = match s.parse::<i32>() {
        Ok(i) => i,
        Err(_e) => -1,
    };
    println!("{:?}", i);
    s = "12u3";
    i = match s.parse::<i32>() {
        Ok(i) => i,
        Err(_e) => -1,
    };
    println!("{:?}", i);
}

输出

123
-1

23. Convert real number to string with 2 decimal places

Given a real number x, create its string representation s with 2 decimal digits following the dot.

给定一个实数,小数点后保留两位小数

package main
import "fmt"
func main() {
  x := 3.14159
  s := fmt.Sprintf("%.2f", x)
  fmt.Println(s)
}

输出

fn main() {
    let x = 42.1337;
    let s = format!("{:.2}", x);
    println!("{}", s);
}

输出

42.13


24. Assign to string the japanese word ネコ

Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)

声明一个新的字符串s,并用文字值“ネコ”初始化它(在日语中是“cat”的意思)

package main
import "fmt"
func main() {
  s := "ネコ"
  fmt.Println(s)
}
fn main() {
    let s = "ネコ";
    println!("{}", s);
}

25. Send a value to another thread

Share the string value "Alan" with an existing running process which will then display "Hello, Alan"

将字符串值“Alan”与现有的正在运行的进程共享,该进程将显示“你好,Alan”

ch <- "Alan"
package main
import (
  "fmt"
  "time"
)
func main() {
  ch := make(chan string)
  go func() {
    v := <-ch
    fmt.Printf("Hello, %v\n", v)
  }()
  ch <- "Alan"
  // Make sure the non-main goroutine had the chance to finish.
  time.Sleep(time.Second)
}

The receiver goroutine blocks reading the string channel ch. The current goroutine sends the value to ch. A goroutine is like a thread, but more lightweight.

use std::thread;
use std::sync::mpsc::channel;
fn main() {
    let (send, recv) = channel();
    let handle = thread::spawn(move || loop {
        let msg = recv.recv().unwrap();
        println!("Hello, {:?}", msg);
    });
    send.send("Alan").unwrap();
    handle.join().unwrap();
}

输出 Hello, "Alan"


26. Create a 2-dimensional array

Declare and initialize a matrix x having m rows and n columns, containing real numbers.

创建一个二维数组

声明并初始化一个有m行n列的矩阵x,包含实数。

const m, n = 3, 4
var x [m][n]float64
package main
import "fmt"
func main() {
  const m, n = 3, 4
  var x [m][n]float64
  x[1][2] = 8
  fmt.Println(x)
}

or

package main
import "fmt"
func main() {
  x := make2D(2, 3)
  x[1][1] = 8
  fmt.Println(x)
}
func make2D(m, n int) [][]float64 {
  buf := make([]float64, m*n)
  x := make([][]float64, m)
  for i := range x {
    x[i] = buf[:n:n]
    buf = buf[n:]
  }
  return x
}
fn main() {
    const M: usize = 4;
    const N: usize = 6;
    let x = vec![vec![0.0f64; N]; M];
    println!("{:#?}", x);
}

输出

[
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
]
fn main() {
  const M: usize = 3;
  const N: usize = 4;
  let mut x = [[0.0; N] ; M];
  x[1][3] = 5.0;
  println!("{:#?}", x);
}

输出

[
    [
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        5.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
    ],
]

27. Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

创建一个三维数组

声明并初始化一个三维数组x,它有m,n,p维边界,并且包含实数。


const m, n, p = 2, 2, 3
var x [m][n][p]float64
package main
import "fmt"
func main() {
  const m, n, p = 2, 2, 3
  var x [m][n][p]float64
  x[1][0][2] = 9
  // Value of x
  fmt.Println(x)
  // Type of x
  fmt.Printf("%T", x)
}
[[[0 0 0] [0 0 0]] [[0 0 9] [0 0 0]]]
[2][2][3]float64

or

func make3D(m, n, p int) [][][]float64 {
  buf := make([]float64, m*n*p)
  x := make([][][]float64, m)
  for i := range x {
    x[i] = make([][]float64, n)
    for j := range x[i] {
      x[i][j] = buf[:p:p]
      buf = buf[p:]
    }
  }
  return x
}
package main
import "fmt"
func main() {
  x := make3D(2, 2, 3)
  x[1][0][2] = 9
  fmt.Println(x)
}
func make3D(m, n, p int) [][][]float64 {
  buf := make([]float64, m*n*p)
  x := make([][][]float64, m)
  for i := range x {
    x[i] = make([][]float64, n)
    for j := range x[i] {
      x[i][j] = buf[:p:p]
      buf = buf[p:]
    }
  }
  return x
}
[[[0 0 0] [0 0 0]] [[0 0 9] [0 0 0]]]
fn main() {
    let m = 4;
    let n = 6;
    let p = 2;
    let x = vec![vec![vec![0.0f64; p]; n]; m];
    println!("{:#?}", x);
}

输出

[
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
]
fn main() {
    const M: usize = 4;
    const N: usize = 6;
    const P: usize = 2;
    let x = [[[0.0f64; P]; N]; M];
    println!("{:#?}", x);
}

输出

[
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
]

28. Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

按x->p的升序对类似数组的集合项的元素进行排序,其中p是项中对象的项类型的字段。

package main
import "fmt"
import "sort"
type Item struct {
  label string
  p     int
  lang  string
}
type ItemPSorter []Item
func (s ItemPSorter) Len() int           { return len(s) }
func (s ItemPSorter) Less(i, j int) bool { return s[i].p < s[j].p }
func (s ItemPSorter) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func sortItems(items []Item) {
  sorter := ItemPSorter(items)
  sort.Sort(sorter)
}
func main() {
  items := []Item{
    {"twelve", 12, "english"},
    {"six", 6, "english"},
    {"eleven", 11, "english"},
    {"zero", 0, "english"},
    {"two", 2, "english"},
  }
  fmt.Println("Unsorted: ", items)
  sortItems(items)
  fmt.Println("Sorted: ", items)
}
Unsorted:  [{twelve 12 english} {six 6 english} {eleven 11 english} {zero 0 english} {two 2 english}]
Sorted:  [{zero 0 english} {two 2 english} {six 6 english} {eleven 11 english} {twelve 12 english}]

or

package main
import "fmt"
import "sort"
type Item struct {
  label string
  p     int
  lang  string
}
func main() {
  items := []Item{
    {"twelve", 12, "english"},
    {"six", 6, "english"},
    {"eleven", 11, "english"},
    {"zero", 0, "english"},
    {"two", 2, "english"},
  }
  fmt.Println("Unsorted: ", items)
  less := func(i, j int) bool {
    return items[i].p < items[j].p
  }
  sort.Slice(items, less)
  fmt.Println("Sorted: ", items)
}
Unsorted:  [{twelve 12 english} {six 6 english} {eleven 11 english} {zero 0 english} {two 2 english}]
Sorted:  [{zero 0 english} {two 2 english} {six 6 english} {eleven 11 english} {twelve 12 english}]
#[derive(Debug)]
struct Foo {
    p: i32,
}
fn main() {
    let mut items = vec![Foo { p: 3 }, Foo { p: 1 }, Foo { p: 2 }, Foo { p: 4 }];
    items.sort_by(|a, b| a.p.cmp(&b.p));
    println!("{:?}", items);
}

输出

[Foo { p: 1 }, Foo { p: 2 }, Foo { p: 3 }, Foo { p: 4 }]

or

#[derive(Debug)]
struct Foo {
    p: i32,
}
fn main() {
    let mut items = vec![Foo { p: 3 }, Foo { p: 1 }, Foo { p: 2 }, Foo { p: 4 }];
    items.sort_by_key(|x| x.p);
    println!("{:?}", items);
}

输出

[Foo { p: 1 }, Foo { p: 2 }, Foo { p: 3 }, Foo { p: 4 }]

29. Remove item from list, by its index

Remove i-th item from list items. This will alter the original list or return a new list, depending on which is more idiomatic. Note that in most languages, the smallest valid value for i is 0.

从列表项中删除第I项。 这将改变原来的列表或返回一个新的列表,这取决于哪个更习惯。 请注意,在大多数语言中,I的最小有效值是0。

package main
import (
  "fmt"
)
func main() {
  items := []string{"a", "b", "c", "d", "e", "f"}
  fmt.Println(items)
  i := 2
  items = append(items[:i], items[i+1:]...)
  fmt.Println(items)
}
[a b c d e f]
[a b d e f]

or

copy(items[i:], items[i+1:])
items[len(items)-1] = nil
items = items[:len(items)-1]
fn main() {
    let mut v = vec![1, 2, 3];
    assert_eq!(v.remove(1), 2);
    assert_eq!(v, [1, 3]);
}

30. Parallelize execution of 1000 independent tasks

Launch the concurrent execution of procedure f with parameter i from 1 to 1000. Tasks are independent and f(i) doesn't return any value. Tasks need not run all at the same time, so you may use a pool.

用参数I从1到1000启动程序f的并发执行。 任务是独立的,f(i)不返回值。 任务不需要同时运行,所以可以使用pools

import "sync"
wg := sync.WaitGroup{}
wg.Add(1000)
for i := 1; i <= 1000; i++ {
  go func(j int) {
          f(j)
          wg.Done()
        }(i)
}
wg.Wait()
package main
import (
  "fmt"
  "math/rand"
  "time"
)
func f(i int) {
  d := rand.Int() % 10000
  time.Sleep(time.Duration(d))
  fmt.Printf("Hello %v\n", i)
}
func main() {
  for i := 1; i <= 1000; i++ {
    go f(i)
  }
  time.Sleep(4 * time.Second)
}
use std::thread;
fn main() {
    let threads: Vec<_> = (0..1000).map(|i| thread::spawn(move || f(i))).collect();
    for thread in threads {
        thread.join();
    }
}
fn f(i: i32) {
    println!("{}", i);
}

or

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