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

news/2024/4/29 9:01:00/文章来源:https://blog.csdn.net/techdashen/article/details/131943770
alt

题图来自 Go vs. Rust: The Ultimate Performance Battle


241. Yield priority to other threads

Explicitly decrease the priority of the current process, so that other execution threads have a better chance to execute now. Then resume normal execution and call function busywork.

将优先权让给其他线程

package main

import (
 "fmt"
 "runtime"
 "time"
)

func main() {
 go fmt.Println("aaa")
 go fmt.Println("bbb")
 go fmt.Println("ccc")
 go fmt.Println("ddd")
 go fmt.Println("eee")

 runtime.Gosched()
 busywork()

 time.Sleep(100 * time.Millisecond)
}

func busywork() {
 fmt.Println("main")
}

After Gosched, the execution of the current goroutine resumes automatically.

aaa
eee
ccc
bbb
ddd
main

::std::thread::yield_now();
busywork();

242. Iterate over a set

Call a function f on each element e of a set x.

迭代一个集合

package main

import "fmt"

type T string

func main() {
 // declare a Set (implemented as a map)
 x := make(map[T]bool)

 // add some elements
 x["A"] = true
 x["B"] = true
 x["B"] = true
 x["C"] = true
 x["D"] = true

 // remove an element
 delete(x, "C")

 for e := range x {
  f(e)
 }
}

func f(e T) {
 fmt.Printf("contains element %v \n", e)
}

contains element A 
contains element B 
contains element D 

use std::collections::HashSet;

fn main() {
    let mut x = HashSet::new();
    x.insert("a");
    x.insert("b");

    for item in &x {
        f(item);
    }
}

fn f(s: &&str) {
    println!("Element {}", s);
}

x is a HashSet

Element a
Element b

243. Print list

Print the contents of list a on the standard output.

打印 list

package main

import (
 "fmt"
)

func main() {
 {
  a := []int{112233}
  fmt.Println(a)
 }

 {
  a := []string{"aa""bb"}
  fmt.Println(a)
 }

 {
  type Person struct {
   First string
   Last  string
  }
  x := Person{
   First: "Jane",
   Last:  "Doe",
  }
  y := Person{
   First: "John",
   Last:  "Doe",
  }
  a := []Person{x, y}
  fmt.Println(a)
 }

 {
  x, y := 1122
  a := []*int{&x, &y}
  fmt.Println(a)
 }
}

[11 22 33]
[aa bb]
[{Jane Doe} {John Doe}]
[0xc000018080 0xc000018088]

fn main() {
    let a = [112233];

    println!("{:?}", a);
}

[11, 22, 33]


244. Print map

Print the contents of map m to the standard output: keys and values.

打印 map

package main

import (
 "fmt"
)

func main() {
 {
  m := map[string]int{
   "eleven":     11,
   "twenty-two"22,
  }
  fmt.Println(m)
 }

 {
  x, y := 78
  m := map[string]*int{
   "seven": &x,
   "eight": &y,
  }
  fmt.Println(m)
 }
}

map[eleven:11 twenty-two:22]
map[eight:0xc000100040 seven:0xc000100028]

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    m.insert("Áron".to_string(), 23);
    m.insert("Béla".to_string(), 35);
    println!("{:?}", m);
}

{"Béla": 35, "Áron": 23}


245. Print value of custom type

Print the value of object x having custom type T, for log or debug.

打印自定义类型的值

package main

import (
 "fmt"
)

// T represents a tank. It doesn't implement fmt.Stringer.
type T struct {
 name      string
 weight    int
 firePower int
}

// Person implement fmt.Stringer.
type Person struct {
 FirstName   string
 LastName    string
 YearOfBirth int
}

func (p Person) String() string {
 return fmt.Sprintf("%s %s, born %d", p.FirstName, p.LastName, p.YearOfBirth)
}

func main() {
 {
  x := T{
   name:      "myTank",
   weight:    100,
   firePower: 90,
  }

  fmt.Println(x)
 }
 {
  x := Person{
   FirstName:   "John",
   LastName:    "Doe",
   YearOfBirth: 1958,
  }

  fmt.Println(x)
 }
}

Will be more relevant if T implements fmt.Stringer

{myTank 100 90}
John Doe, born 1958

#[derive(Debug)]

// T represents a tank
struct T<'a> {
    name: &'a str,
    weight: &'a i32,
    fire_power: &'a i32,
}

fn main() {
    let x = T {
        name: "mytank",
        weight: &100,
        fire_power: &90,
    };

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

Implement fmt::Debug or fmt::Display for T

T { name: "mytank", weight: 100, fire_power: 90 }


246. Count distinct elements

Set c to the number of distinct elements in list items.

计算不同的元素的数量

package main

import (
 "fmt"
)

func main() {
 type T string
 items := []T{"a""b""b""aaa""c""a""d"}
 fmt.Println("items has"len(items), "elements")

 distinct := make(map[T]bool)
 for _, v := range items {
  distinct[v] = true
 }
 c := len(distinct)

 fmt.Println("items has", c, "distinct elements")
}
items has 7 elements
items has 5 distinct elements

use itertools::Itertools;

fn main() {
    let items = vec!["víz""árvíz""víz""víz""ár""árvíz"];
    let c = items.iter().unique().count();
    println!("{}", c);
}

3


247. Filter list in-place

Remove all the elements from list x that don't satisfy the predicate p, without allocating a new list.
Keep all the elements that do satisfy p.
For languages that don't have mutable lists, refer to idiom #57 instead.

就地筛选列表

package main

import "fmt"

type T int

func main() {
 x := []T{12345678910}
 p := func(t T) bool { return t%2 == 0 }

 j := 0
 for i, v := range x {
  if p(v) {
   x[j] = x[i]
   j++
  }
 }
 x = x[:j]

 fmt.Println(x)
}

[2 4 6 8 10]

or

package main

import "fmt"

type T int

func main() {
 var x []*T
 for _, v := range []T{12345678910} {
  t := new(T)
  *t = v
  x = append(x, t)
 }
 p := func(t *T) bool { return *t%2 == 0 }

 j := 0
 for i, v := range x {
  if p(v) {
   x[j] = x[i]
   j++
  }
 }
 for k := j; k < len(x); k++ {
  x[k] = nil
 }
 x = x[:j]

 for _, pt := range x {
  fmt.Print(*pt, " ")
 }
}

2 4 6 8 10


fn p(t: i32) -> bool {
    t % 2 == 0
}

fn main() {
    let mut x = vec![12345678910];
    let mut j = 0;
    for i in 0..x.len() {
        if p(x[i]) {
            x[j] = x[i];
            j += 1;
        }
    }
    x.truncate(j);
    println!("{:?}", x);
}

[2, 4, 6, 8, 10]

or

fn p(t: &i64) -> bool {
    t % 2 == 0
}

fn main() {
    let mut x: Vec<i64> = vec![12345678910];

    x.retain(p);

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

[2, 4, 6, 8, 10]


249. Declare and assign multiple variables

Define variables a, b and c in a concise way. Explain if they need to have the same type.

声明并分配多个变量

package main

import (
 "fmt"
)

func main() {
 // a, b and c don't need to have the same type.

 a, b, c := 42"hello"5.0

 fmt.Println(a, b, c)
 fmt.Printf("%T %T %T \n", a, b, c)
}

42 hello 5
int string float64 

fn main() {
    // a, b and c don't need to have the same type.

    let (a, b, c) = (42"hello"5.0);

    println!("{} {} {}", a, b, c);
}

42 hello 5


251. Parse binary digits

Extract integer value i from its binary string representation s (in radix 2) E.g. "1101" -> 13

解析二进制数字

package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 s := "1101"
 fmt.Println("s is", reflect.TypeOf(s), s)

 i, err := strconv.ParseInt(s, 20)
 if err != nil {
  panic(err)
 }

 fmt.Println("i is", reflect.TypeOf(i), i)
}

s is string 1101
i is int64 13

fn main() {
    let s = "1101"// binary digits
    
    let i = i32::from_str_radix(s, 2).expect("Not a binary number!");
    
    println!("{}", i);
}

13


252. Conditional assignment

Assign to variable x the value "a" if calling the function condition returns true, or the value "b" otherwise.

条件赋值

package main

import (
 "fmt"
)

func main() {
 var x string
 if condition() {
  x = "a"
 } else {
  x = "b"
 }

 fmt.Println(x)
}

func condition() bool {
 return "Socrates" == "dog"
}

b


x = if condition() { "a" } else { "b" };

258. Convert list of strings to list of integers

Convert the string values from list a into a list of integers b.

将字符串列表转换为整数列表

package main

import (
 "fmt"
 "strconv"
)

func main() {
 a := []string{"11""22""33"}

 b := make([]intlen(a))
 var err error
 for i, s := range a {
  b[i], err = strconv.Atoi(s)
  if err != nil {
   panic(err)
  }
 }

 fmt.Println(b)
}

[11 22 33]


fn main() {
    let a: Vec<&str> = vec!["11""-22""33"];

    let b: Vec<i64> = a.iter().map(|x| x.parse::<i64>().unwrap()).collect();

    println!("{:?}", b);
}

[11, -22, 33]


259. Split on several separators

Build list parts consisting of substrings of input string s, separated by any of the characters ',' (comma), '-' (dash), '_' (underscore).

在几个分隔符上拆分

package main

import (
 "fmt"
 "regexp"
)

func main() {
 s := "2021-03-11,linux_amd64"

 re := regexp.MustCompile("[,\\-_]")
 parts := re.Split(s, -1)
 
 fmt.Printf("%q", parts)
}

["2021" "03" "11" "linux" "amd64"]


fn main() {
    let s = "2021-03-11,linux_amd64";

    let parts: Vec<_> = s.split(&[',''-''_'][..]).collect();

    println!("{:?}", parts);
}

["2021", "03", "11", "linux", "amd64"]


266. Repeating string

Assign to string s the value of string v, repeated n times and write it out.
E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"

重复字符串

package main

import (
 "fmt"
 "strings"
)

func main() {
 v := "abc"
 n := 5

 s := strings.Repeat(v, n)

 fmt.Println(s)
}

abcabcabcabcabc


fn main() {
    let v = "abc";
    let n = 5;

    let s = v.repeat(n);
    println!("{}", s);
}

abcabcabcabcabc


本文由 mdnice 多平台发布

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_335759.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SpringBoot 配置⽂件

1.配置文件作用 整个项⽬中所有重要的数据都是在配置⽂件中配置的&#xff0c;⽐如&#xff1a; 数据库的连接信息&#xff08;包含⽤户名和密码的设置&#xff09;&#xff1b;项⽬的启动端⼝&#xff1b;第三⽅系统的调⽤秘钥等信息&#xff1b;⽤于发现和定位问题的普通⽇…

VMware horizon 8 建立手动桌面池

准备一台win10的虚拟机&#xff0c;改静态IP,计算机名&#xff0c;加入域&#xff0c;把Agent软件上传到机器中。 2&#xff1a;右键管理员身份安装程序。 一般默认 根据自己实际情况选择 启用桌面远程功能 安装完成 安装完成以后创建一个快照&#xff0c;以后是好知道机…

模拟Stevens Lewis描述的小型飞机纵向动力学的非线性动态反演控制器研究(Matlab代码实现)

目录 &#x1f4a5;1 概述 &#x1f4da;2 运行结果 &#x1f389;3 参考文献 &#x1f308;4 Matlab代码实现 &#x1f4a5;1 概述 针对Stevens和Lewis描述的小型飞机纵向动力学的非线性动态&#xff0c;研究非线性动态反演控制器可以是一个有趣的课题。动态反演控制器的目标…

会捷通云视讯 list 目录文件泄露漏洞

劳动永远是医治精神创伤的良药。 漏洞描述 会捷通云视讯某个文件 list参数 存在目录文件泄露漏洞&#xff0c;攻击者通过漏洞可以获取一些敏感信息 漏洞复现 构造payload访问漏洞url&#xff1a; /him/api/rest/V1.0/system/log/list?filePath../漏洞证明&#xff1a; 文…

【iOS】KVOKVC原理

1 KVO 键值监听 1.1 KVO简介 KVO的全称是Key-Value Observing&#xff0c;俗称"键值监听"&#xff0c;可以用于监听摸个对象属性值得改变。 KVO一般通过以下三个步骤使用&#xff1a; // 1. 添加监听 [self.student1 addObserver:self forKeyPath:"age"…

音视频——帧内预测

H264编码(帧内预测) 在帧内预测模式中&#xff0c;预测块P是基于已编码重建块和当前块形成的。对亮度像素而言&#xff0c;P块用于44子块或者1616宏块的相关操作。44亮度子块有9种可选预测模式&#xff0c;独立预测每一个44亮度子块&#xff0c;适用于带有大量细节的图像编码&…

云安全攻防(二)之 云原生安全

云原生安全 什么是云原生安全&#xff1f;云原生安全包含两层含义&#xff1a;面向云原生环境的安全和具有云原生特征的安全 面向云原生环境的安全 面向云原生环境的安全的目标是防护云原生环境中的基础设施、编排系统和微服务系统的安全。这类安全机制不一定会具有云原生的…

交叉编译----宿主机x86 ubuntu 64位-目标机ARMv8 aarch64

1.交叉编译是什么&#xff0c;为什么要交叉编译 编译&#xff1a;在一个平台上生成在该平台上的可执行代码交叉编译&#xff1a;在一个平台上生成在另一个平台上的可执行代码交叉编译的例子&#xff1a;如51单片机的可执行代码&#xff08;hex文件&#xff09;是在集成环境kei…

【C#】医学实验室云LIS检验信息系统源码 采用B/S架构

基于B/S架构的医学实验室云LIS检验信息系统&#xff0c;整个系统的运行基于WEB层面&#xff0c;只需要在对应的工作台安装一个浏览器软件有外网即可访问&#xff0c;技术架构&#xff1a;Asp.NET CORE 3.1 MVC SQLserver Redis等。 一、系统概况 本系统是将各种生化、免疫、…

R语言无法调用stats.dll的问题解决方案[补充]

写在前面 在去年10月份&#xff0c;出过一起关于R语言无法调用stats.dll的问题解决方案,今天&#xff08;你看到后是昨天&#xff09;不知道为什么&#xff0c;安装包&#xff0c;一直安装不了&#xff0c;真的是炸裂了。后面再次把R与Rstuido升级。说实话&#xff0c;我是真不…

el-table 表格头部合并

<el-table v-loading"listLoading" :key"tableKey" :data"list" stripe border fit highlight-current-rowstyle"width: 100%;" size"mini"><el-table-column label"第一行" align"center">…

同一份数据,Redis为什么要存两次

Redis作为目前最主流的高性能缓存&#xff0c;里面有很多精妙的设计&#xff0c;其中有一种数据类型&#xff0c;当在存储的时候会同时采用两种数据结构来进行分别存储&#xff0c;那么 Redis 为什么要这么做呢&#xff1f;这么做会造成同一份数据占用两倍空间吗&#xff1f; …

【概率预测】对风力发电进行短期概率预测的分析研究(Matlab代码实现)

目录 &#x1f4a5;1 概述 &#x1f4da;2 运行结果 &#x1f389;3 参考文献 &#x1f308;4 Matlab代码、数据、详细文章 &#x1f4a5;1 概述 概率预测是一种通过概率统计方法对未来事件进行预测的技术。在风力发电的短期预测中&#xff0c;概率预测可以用来对未来风速和风…

QT--day2(信号与槽,多界面跳转)

第一个界面头文件&#xff1a; #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QIcon> //图标头文件 #include <QPushButton> //按钮类头文件QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACEclass Widget : public…

爬虫001_Pip指令使用_包管理工具_pip的使用_和源的切换---python工作笔记019

scrapy是一个爬虫的框架 确认一下pip这个python中的包管理工具是否已经安装好了 python的环境变量配置完了以后,还需要配置一下pip的环境变量 把这个目录配置好,这个pip的环境变量的配置很简单不多说了. 我们用pip安装一下包,我们安装到上面这个路径里面,就是python的安装路…

MATLAB基础知识回顾

目录 1.帮助命令 2.数据类型 3.元胞数组和结构体 4.矩阵操作 4.1 矩阵的定义与构造 4.2 矩阵的四则运算 4.3 矩阵的下标 5.程序结构 5.1 for循环结构 5.2 分支结构 7.基本绘图操作 7.1.二维平面绘图 6.2 三维立体绘图 7.图形的保存与导出 8.补充 语句后⾯加;的作…

C语言中的数组(详解)

C语言中的数组&#xff08;详解&#xff09; 一、一维数组1.一维数组的创建2.数组的初始化3.一维数组的使用4.一维数组在内存中的存储二、二维数组1.二维数组的创建2.二维数组的初始化3.二维数组的使用4.二维数组在内存中的存储三、数组越界四、数组作为函数参数1.冒泡排序2.数…

SpringBoot 集成 Elasticsearch

一、版本 spring-boot版本&#xff1a;2.3.7.RELEASEElasticsearch7.8.0版本说明详见 二、Elasticsearch 下载和安装 Elasticsearch 下载 kibana下载 ik分词器下载 配置IK分词器 2.1 解压&#xff0c;在elasticsearch-7.8.0\plugins 路径下新建ik目录 2.2 将ik分词器解压放…

java中判断list是否为空

java中判断list是否为空是日常代码中经常遇到的问题。最近发现一个Utils提供的方法可以一步判断。 废话不多说&#xff0c;直接上代码&#xff01; ArrayList<String> arrayList new ArrayList<>(); System.out.println("集合1&#xff1a;" Collecti…

【数据结构】_4.List接口实现类LinkedList与链表

目录 1.链表的结构与特点 1.1 链表的结构&#xff1a; 1.2 链表的特点&#xff1a; 2. 不带头单链表的模拟实现 3. 单链表OJ 3.1 题目1&#xff1a;移除链表元素: 3.2 题目2&#xff1a;反转一个单链表 3.3 题目3&#xff1a;返回链表的中间结点 3.4 题目4&#xff1…