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

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

image.png


41. Reverse a string


反转字符串

package main
import "fmt"
func Reverse(s string) string {
  runes := []rune(s)
  for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
    runes[i], runes[j] = runes[j], runes[i]
  }
  return string(runes)
}
func main() {
  input := "The quick brown 狐 jumped over the lazy 犬"
  fmt.Println(Reverse(input))
  // Original string unaltered
  fmt.Println(input)
}

输出

犬 yzal eht revo depmuj 狐 nworb kciuq ehT
The quick brown 狐 jumped over the lazy 犬


let t = s.chars().rev().collect::<String>();

or

fn main() {
    let s = "lorém ipsüm dolör sit amor ❤ ";
    let t: String = s.chars().rev().collect();
    println!("{}", t);
}


输出

❤ roma tis rölod müspi mérol


42. Continue outer loop


Print each item v of list a which in not contained in list b. For this, write an outer loop to iterate on a and an inner loop to iterate on b.


打印列表a中不包含在列表b中的每个项目v。 为此,编写一个外部循环来迭代a,编写一个内部循环来迭代b。

package main
import "fmt"
func printSubtraction(a []int, b []int) {
mainloop:
  for _, v := range a {
    for _, w := range b {
      if v == w {
        continue mainloop
      }
    }
    fmt.Println(v)
  }
}
func main() {
  a := []int{1, 2, 3, 4}
  b := []int{2, 4, 6, 8}
  printSubtraction(a, b)
}

mainloop is a label used to refer to the outer loop.

输出

1
3
fn main() {
    let a = ['a', 'b', 'c', 'd', 'e'];
    let b = [     'b',      'd'     ];
    'outer: for va in &a {
        for vb in &b {
            if va == vb {
                continue 'outer;
            }
        }
        println!("{}", va);
    }
}

'outer is a label used to refer to the outer loop. Labels in Rust start with a '.

输出

rust

复制代码

a
c
e

43. Break outer loop


Look for a negative value v in 2D integer matrix m. Print it and stop searching.

在2D整数矩阵m中寻找一个负值v,打印出来,停止搜索。

package main
import "fmt"
import "os"
var m = [][]int{
  {1, 2, 3},
  {11, 0, 30},
  {5, -20, 55},
  {0, 0, -60},
}
func main() {
mainloop:
  for i, line := range m {
    fmt.Fprintln(os.Stderr, "Searching in line", i)
    for _, v := range line {
      if v < 0 {
        fmt.Println("Found ", v)
        break mainloop
      }
    }
  }
  fmt.Println("Done.")
}

mainloop is a label used to refer to the outer loop.

输出

Searching in line 0
Searching in line 1
Searching in line 2
Found  -20
Done.
fn main() {
    let m = vec![
        vec![1, 2, 3],
        vec![11, 0, 30],
        vec![5, -20, 55],
        vec![0, 0, -60],
    ];
    'outer: for v in m {
        'inner: for i in v {
            if i < 0 {
                println!("Found {}", i);
                break 'outer;
            }
        }
    }
}

Loop label syntax is similar to lifetimes.

输出

Found -20


44. Insert element in list


Insert element x at position i in list s. Further elements must be shifted to the right.

在列表s的位置I插入元素x。其他元素必须向右移动。

package main
import "fmt"
func main() {
  s := make([]int, 2)
  s[0] = 0
  s[1] = 2
  fmt.Println(s)  
  // insert one at index one
  s = append(s, 0)
  copy(s[2:], s[1:])
  s[1] = 1
  fmt.Println(s)
}

输出

[0 2]
[0 1 2]
fn main() {
    let mut vec = vec![1, 2, 3];
    vec.insert(1, 4);
    assert_eq!(vec, [1, 4, 2, 3]);
    vec.insert(4, 5);
    assert_eq!(vec, [1, 4, 2, 3, 5]);
}


45. Pause execution for 5 seconds


在继续下一个指令之前,在当前线程中休眠5秒钟。

package main
import (
  "fmt"
  "time"
)
func main() {
  time.Sleep(5 * time.Second)
  fmt.Println("Done.")
}
use std::{thread, time};
thread::sleep(time::Duration::from_secs(5));

use std::{thread, time};thread::sleep(time::Duration::from_secs(5));


46. Extract beginning of string (prefix)


Create string t consisting of the 5 first characters of string s. Make sure that multibyte characters are properly handled.

创建由字符串s的前5个字符组成的字符串t。 确保正确处理多字节字符。

package main
import "fmt"
func main() {
  s := "Привет"
  t := string([]rune(s)[:5])
  fmt.Println(t)
}

输出

Приве
fn main() {
    let s = "été 😁 torride";
    let t = s.char_indices().nth(5).map_or(s, |(i, _)| &s[..i]);
    println!("{}", t);
}

输出

été 😁


47. Extract string suffix


Create string t consisting in the 5 last characters of string s. Make sure that multibyte characters are properly handled.


创建由字符串s的最后5个字符组成的字符串t。 确保正确处理多字节字符

package main
import "fmt"
func main() {
  s := "hello, world! 문자"
  t := string([]rune(s)[len([]rune(s))-5:])
  fmt.Println(t)
}

输出

d! 문자

fn main() {
    let s = "tükörfúrógép";
    let last5ch = s.chars().count() - 5;
    let s2: String = s.chars().skip(last5ch).collect();
    println!("{}", s2);
}

输出

rógép


48. Multi-line string literal

Assign to variable s a string literal consisting in several lines of text, including newlines.

给变量s赋值一个由几行文本组成的字符串,包括换行符。

package main
import (
  "fmt"
)
func main() {
  s := `Huey
Dewey
Louie`
  fmt.Println(s)
}

输出

Huey
Dewey
Louie
fn main() {
    let s = "line 1
line 2
line 3";
    print!("{}", &s);
}

输出

line 1
line 2
line 3

or

fn main() {
    let s = r#"Huey
Dewey
Louie"#;
    print!("{}", &s);
}

输出

Huey
Dewey
Louie

49. Split a space-separated string


拆分用空格分隔的字符串

Build list chunks consisting in substrings of input string s, separated by one or more space characters.

构建由输入字符串的子字符串组成的列表块,由一个或多个空格字符分隔。

package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "Un dos tres"
  chunks := strings.Split(s, " ")
  fmt.Println(len(chunks))
  fmt.Println(chunks)
  s = " Un dos tres "
  chunks = strings.Split(s, " ")
  fmt.Println(len(chunks))
  fmt.Println(chunks)
  s = "Un  dos"
  chunks = strings.Split(s, " ")
  fmt.Println(len(chunks))
  fmt.Println(chunks)
}

输出

3
[Un dos tres]
5
[ Un dos tres ]
3
[Un  dos]

or

package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "hello world"
  chunks := strings.Fields(s)
  fmt.Println(chunks)
}

输出为

[hello world]

and

package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "Un dos tres"
  chunks := strings.Fields(s)
  fmt.Println(len(chunks))
  fmt.Println(chunks)
  s = " Un dos tres "
  chunks = strings.Fields(s)
  fmt.Println(len(chunks))
  fmt.Println(chunks)
  s = "Un  dos"
  chunks = strings.Fields(s)
  fmt.Println(len(chunks))
  fmt.Println(chunks)
}

输出

3
[Un dos tres]
3
[Un dos tres]
2
[Un dos]

strings.Fields 就只能干这个事儿

fn main() {
    let s = "What a  mess";
    let chunks: Vec<_> = s.split_whitespace().collect();
    println!("{:?}", chunks);
}

输出

["What", "a", "mess"]

or

fn main() {
    let s = "What a  mess";
    let chunks: Vec<_> = s.split_ascii_whitespace().collect();
    println!("{:?}", chunks);
}

书橱

["What", "a", "mess"]

or

fn main() {
    let s = "What a  mess";
    let chunks: Vec<_> = s.split(' ').collect();
    println!("{:?}", chunks);
}

输出

["What", "a", "", "mess"]


50. Make an infinite loop


写一个无限循环

for {
  // Do something
}
package main
import "fmt"
func main() {
  k := 0
  for {
    fmt.Println("Hello, playground")
    k++
    if k == 5 {
      break
    }
  }
}

输出

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