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

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.mzph.cn/news/10336.shtml

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

相关文章

7.27 作业 QT

要求&#xff1a; 结果图&#xff1a; clock.pro: QT core gui QT texttospeechgreaterThan(QT_MAJOR_VERSION, 4): QT widgetsCONFIG c11# The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated …

Bootstrap框架(组件)

目录 前言一&#xff0c;组件1.1&#xff0c;字体图标1.2&#xff0c;下拉菜单组件1.2.1&#xff0c;基本下拉菜单1.2.2&#xff0c;按钮式下拉菜单 1.3&#xff0c;导航组件1.3.1&#xff0c;选项卡导航1.3.2&#xff0c;胶囊式导航1.3.3&#xff0c;自适应导航1.3.4&#xff…

React 组件使用

React 组件是一个 js 函数&#xff0c;函数可以添加 jsx 标记 当前页使用组件&#xff0c;基本使用 注意&#xff1a;组件的名称&#xff0c;第一个字母一定要大写&#xff0c;否则会报错 import { createRoot } from "react-dom/client"; import "./index.c…

(三)springboot实战——web新特性之函数式实现

前言 本节内容我们主要介绍一下web访问的另一种形式&#xff0c;通过函数式web实现一个restful风格的http请求案例。函数式web是spring5.2之后的一个新特性&#xff0c;可以通过函数去定义web请求的处理流程&#xff0c;使得代码更为简洁&#xff0c;耦合性也降低了。 正文 …

[Linux] 初识应用层协议: 序列化与反序列化、编码与解码、jsoncpp简单使用...

写在应用层之前 有关Linux网络, 之前的文章已经简单演示介绍了UDP、TCP套接字编程 相关文章: [Linux] 网络编程 - 初见UDP套接字编程: 网络编程部分相关概念、TCP、UDP协议基本特点、网络字节序、socket接口使用、简单的UDP网络及聊天室实现… [Linux] 网络编程 - 初见TCP套接…

国产化 | 走近人大金仓-KingbaseES数据库

引入 事务隔离级别 || KingbaseES数据库 开篇 1、KingbaseES数据库 百度百科&#xff1a;金仓数据库的最新版本为KingbaseES V8&#xff0c; KingbaseES V8在系统的可靠性、可用性、性能和兼容性等方面进行了重大改进&#xff0c;支持多种操作系统和硬件平台支持Unix、Linux…

Ubuntu--科研工具系列

翻译系列 pot-desktop github链接: https://github.com/pot-app/pot-desktop 下载deb Releases pot-app/pot-desktop GitHub 安装过程 在下载好的deb目录下打开终端(自动安装依赖) sudo apt install "XXX.deb" &#xff08;后面可以直接托文件到终端&#…

d3dx9_42.dll丢失怎么解决?这三个方法亲测可修复

最近我在使用计算机时遇到了一个问题&#xff0c;就是d3dx9_42.dll文件丢失的错误提示。初时我对这个错误一无所知&#xff0c;不知道该如何解决。但是经过一番搜索和学习&#xff0c;我终于找到了修复这个问题的方法。d3dx9_42.dll是一个与DirectX相关的动态链接库文件&#x…

网络:TCP/IP协议

1. OSI七层参考模型 应用层 表示层 会话层 传输层 网络层 数据链路层 物理层 2. TCP/IP模型 应用层 传输层 网络层 数据链路层 物理层 3. 各链路层对应的名称 应用层对应的是协议数据单元 传输层对应的是数据段 网络层对应的是数据包 链路层对应的是数据帧 物理层对应的是比特…

Elasticsearch API(二)

文章目录 前言一、Elasticsearch指标ES支持的搜索类型ES的能力ES的写入实时性ES不支持事务 二、Elasticsearch名词节点&#xff08;Node&#xff09;角色&#xff08;Roles&#xff09;索引&#xff08;index&#xff09;文档&#xff08;document&#xff09; 三、Elasticsear…

fastadmin 项目gitee管理

gitee创建一个仓库使用sourcetree等工具拉取代码使用phpstorm远程同步代码到本地设置忽略代码文件 注意&#xff1a;如果是直接把远程代码同步到本地&#xff0c;默认是你在 .gitignore中设置是无效的&#xff0c;代码一样会提交&#xff0c;需要先使用上面的截图去掉缓存&…

VM虚拟机网络配置桥接模式方法步骤

VM虚拟机配置桥接模式&#xff0c;可以让虚拟机和物理主机一样存在于局域网中&#xff0c;可以和主机相通&#xff0c;和互联网相通&#xff0c;和局域网中其它主机相通。 vmware为我们提供了三种网络工作模式&#xff0c;它们分别是&#xff1a;Bridged&#xff08;桥接模式&…

Linux相关

0.需要安装的软件 0.1.VMware&#xff08;虚拟机&#xff09; 0.2.XShell&#xff08;强大的安全终端模拟软件&#xff09; 0.3.XFTP&#xff08;是一个功能强大的SFTP、FTP 文件传输软件&#xff09; 0.4.CentOS XShell和XFTP文件压缩包所在路径 D:\CentOS7 xftp安装默认…

Windows用户如何安装新版本cpolar内网穿透

在科学技术高度发达的今天&#xff0c;我们身边充斥着各种电子产品&#xff0c;这些电子产品不仅为我们的工作带来极大的便利&#xff0c;也让生活变得丰富多彩。我们可以使用便携的电子设备&#xff0c;记录下生活中精彩和有趣的瞬间&#xff0c;并通过互联网方便的与大家分享…

【雕爷学编程】Arduino动手做(172)---WeMos D1开发板模块4

37款传感器与执行器的提法&#xff0c;在网络上广泛流传&#xff0c;其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块&#xff0c;依照实践出真知&#xff08;一定要动手做&#xff09;的理念&#xff0c;以学习和交流为目的&am…

Linux-DHCP安装配置流程

DHCP 介绍 DHCP&#xff08;Dynamic Host Configuration Protocol&#xff09;是一种网络协议&#xff0c;用于在局域网(LAN)中自动分配IP地址和其他网络配置信息给计算机设备。DHCP旨在简化网络管理&#xff0c;允许设备自动获取IP地址&#xff0c;无需手动配置&#xff0c;…

19.主题时钟

主题时钟 html部分 <div class"btn">黑色</div><div class"clock-container"><div class"time">21</div><div class"date">21</div><div class"clock"><div class&qu…

Linux系统MySQL数据库的备份及应用

本节主要学习了MySQL数据库的备份&#xff1a;概念&#xff0c;数据备份的重要性&#xff0c;造成数据丢失的原因&#xff0c;备份的类型&#xff0c;常见的备份方法&#xff0c;实例与应用等。 目录 一、概述 二、数据备份的重要性 三、造成数据丢失的原因 四、备份类型 …

小程序如何上传商品

​小程序作为一种便捷的电商平台&#xff0c;上传商品是非常重要的一步。本文将为你提供一个完整的小程序上传商品教程&#xff0c;帮助你轻松上架自己的商品。 一、进入商品管理页面 在个人中心点击管理入口&#xff0c;然后找到“商品管理”菜单并点击。 2. 点击“添加商品…

MySQL数据库期末项目 图书馆管理系统

1 项目需求分析 1.1 项目名称 图书馆管理系统 1.2 项目功能 在以前大多部分图书馆都是由人工直接管理&#xff0c;其中每天的业务和操作流程非常繁琐复杂&#xff0c;纸质版的登记信息耗费了大量的人力物力。因此图书馆管理系统应运而生&#xff0c;该系统采用智能化设计&#…