当前位置: 首页 > news >正文

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 多平台发布

相关文章:

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

题图来自 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 f…...

【【51单片机DA转换模块】】

爆改直流电机&#xff0c;DA转换器 main.c #include <REGX52.H> #include "Delay.h" #include "Timer0.h"sbit DAP2^1;unsigned char Counter,Compare; //计数值和比较值&#xff0c;用于输出PWM unsigned char i;void main() {Timer0_Init();whil…...

[SQL挖掘机] - 字符串函数 - substring

介绍: substring函数是在mysql中用于提取字符串的一种函数。它接受一个字符串作为输入&#xff0c;并返回从该字符串中指定位置开始的一部分子串。substring函数可以用于获取字符串中的特定字符或子串&#xff0c;以便进行进一步的处理或分析。 用法: 下面是substring函数的…...

第一百一十六天学习记录:C++提高:STL-string(黑马教学视频)

string基本概念 string是C风格的字符串&#xff0c;而string本质上是一个类 string和char区别 1、char是一个指针 2、string是一个类&#xff0c;类内部封装了char*&#xff0c;管理这个字符串&#xff0c;是一个char型的容器。 特点&#xff1a; string类内部封装了很多成员方…...

Meta-Transformer 多模态学习的统一框架

Meta-Transformer是一个用于多模态学习的新框架&#xff0c;用来处理和关联来自多种模态的信息&#xff0c;如自然语言、图像、点云、音频、视频、时间序列和表格数据&#xff0c;虽然各种数据之间存在固有的差距&#xff0c;但是Meta-Transformer利用冻结编码器从共享标记空间…...

tinkerCAD案例:24.Tinkercad 中的自定义字体

tinkerCAD案例&#xff1a;24.Tinkercad 中的自定义字体 原文 Tinkercad Projects Tinkercad has a fun shape in the Shape Generators section that allows you to upload your own font in SVG format and use it in your designs. I’ve used it for a variety of desi…...

list与流迭代器stream_iterator

运行代码&#xff1a; //list与流迭代器 #include"std_lib_facilities.h" //声明Item类 struct Item {string name;int iid;double value;Item():name(" "),iid(0),value(0.0){}Item(string ss,int ii,double vv):name(ss),iid(ii),value(vv){}friend ist…...

九耶:冯·诺伊曼体系

冯诺伊曼体系&#xff08;Von Neumann architecture&#xff09;是一种计算机体系结构&#xff0c;它由匈牙利数学家冯诺伊曼于1945年提出。冯诺伊曼体系是现代计算机体系结构的基础&#xff0c;几乎所有的通用计算机都采用了这种体系结构。 冯诺伊曼体系的核心思想是将计算机硬…...

探索UCI心脏病数据:利用R语言和h2o深度学习构建预测模型

一、引言 随着机器学习模型在实际应用中的广泛应用&#xff0c;人们对于模型的解释性和可理解性日益关注。可解释性机器学习是指能够清晰、透明地解释机器学习模型决策过程的一种方法和技术。在许多领域中&#xff0c;如医疗诊断、金融风险评估和自动驾驶等&#xff0c;解释模型…...

基于 moleculer 微服务架构的智能低代码PaaS 平台源码 可视化开发

低代码开发平台源码 低代码管理系统PaaS 平台 无需代码或通过少量代码就可以快速生成应用程序的开发平台。 本套低代码管理后台可以支持多种企业应用场景&#xff0c;包括但不限于CRM、ERP、OA、BI、IoT、大数据等。无论是传统企业还是新兴企业&#xff0c;都可以使用管理后台…...

xrdp登录显示白屏且红色叉

如上图所示&#xff0c;xrdp登录出现了红色叉加白屏&#xff0c;这是因为不正常关闭导致&#xff0c;解决方法其实挺简单的 #进入/usr/tmp cd /usr/tmp #删除对应用户的kdecache-** 文件&#xff08;我这里使用的是kde桌面&#xff09;&#xff0c;例如删除ywj用户对应的文件 …...

Docker安装 Mysql 8.x 版本

文章目录 Docker安装 Mysql 8.0.22Mysql 创建账号并授权Mysql 数据迁移同版本数据迁移跨版本数据迁移 Mysql 5.x 版本与 Mysql 8.x版本是两个大版本&#xff0c;这里演示安装Mysql 8.x版本 Docker安装 Mysql 8.0.22 # 下载mysql $ docker pull mysql 默认安装最新…...

【数理知识】刚体 rigid body 及刚体的运动

文章目录 1 刚体2 刚体一般运动1 平移运动2 旋转运动 Ref 1 刚体 刚体是指在运动中和受力作用后&#xff0c;形状和大小不变&#xff0c;而且内部各点的相对位置不变的物体。绝对刚体实际上是不存在的&#xff0c;只是一种理想模型&#xff0c;因为任何物体在受力作用后&#…...

【UE5 多人联机教程】03-创建游戏

效果 步骤 打开“UMG_MainMenu”&#xff0c;增加创建房间按钮的点击事件 添加如下节点 其中&#xff0c;“FUNL Fast Create Widget”是插件自带的函数节点&#xff0c;内容如下&#xff1a; “创建会话”节点指游戏成功创建一个会话后&#xff0c;游戏的其他实例即可发现&am…...

【时间序列预测 】M4

【时间序列预测 】M4 论文题目&#xff1a;The M4 Competition: 100,000 time series and 61 forecasting methods 中文题目&#xff1a; 论文链接&#xff1a; 论文代码&#xff1a; 论文团队&#xff1a; 发表时间&#xff1a; DOI: 引用&#xff1a; 引用数&#xff1a; 摘要…...

SpringCloud微服务实战——搭建企业级开发框架(五十三):微信小程序授权登录增加多租户可配置界面

GitEgg框架集成weixin-java-miniapp工具包以实现微信小程序相关接口调用功能&#xff0c;weixin-java-miniapp底层支持多租户扩展。每个小程序都有唯一的appid&#xff0c;weixin-java-miniapp的多租户实现并不是以租户标识TenantId来区分的&#xff0c;而是在接口调用时&#…...

Stability AI推出Stable Diffusion XL 1.0,文本到图像模型

Stability AI宣布推出Stable Diffusion XL 1.0&#xff0c;这是一个文本到图像的模型&#xff0c;该公司将其描述为迄今为止“最先进的”版本。 Stability AI表示&#xff0c;SDXL 1.0能生成更加鲜明准确的色彩&#xff0c;在对比度、光线和阴影方面做了增强&#xff0c;可生成…...

B076-项目实战--宠物上下架 展示 领养 收购订单

目录 上下架功能提供后台宠物列表实现 前台展示前台宠物列表和详情展示店铺展示 领养分析前台后端PetControllerPetServiceImpl 订单需求分析可能产生订单的模块订单模块额外功能 订单设计表设计流程设计 集成基础代码收购订单创建订单前端后端 上下架功能提供 后台宠物列表实…...

【iOS】—— 持久化

文章目录 数据持久化的目的iOS中数据持久化方案数据持久化方式分类内存缓存磁盘缓存 沙盒机制获取应用程序的沙盒路径沙盒目录的获取方式 持久化数据存储方式XML属性列表Preferences偏好设置&#xff08;UserDefaults&#xff09;数据库存储什么是序列化和反序列化&#xff0c;…...

教程 - 在 Vue3+Ts 中引入 CesiumJS 的最佳实践@2023

1. 本篇适用范围与目的 1.1. 适用范围 严格使用 Vue3 TypeScript 的前端项目&#xff0c;包管理器默认使用 pnpm 构建工具使用 Vite4 使用原生 CesiumJS 依赖做应用开发 客户端渲染&#xff0c;因为我不太熟悉 Vue 的服务端渲染&#xff0c;有本篇的介绍后&#xff0c;熟悉…...

最优化方法

一. 图论 1.最小生成树 图的生成树是它的一颗含有其所有顶点的无环连通子图,一 幅加权图的最小生成树(MST)是它的一颗权值(树中的所有边的权值之和) 最小的生成树 • 适用场景&#xff1a;道路规划、通讯网络规划、管道铺设、电线布设等 题目数据 kruskal算法 稀疏图&#x…...

Mongodb 多文档聚合操作处理方法二(Map-reduce 函数)

聚合 聚合操作处理多个文档并返回计算结果。您可以使用聚合操作来&#xff1a; 将多个文档中的值分组在一起。 对分组数据执行操作以返回单个结果。 分析数据随时间的变化。 要执行聚合操作&#xff0c;您可以使用&#xff1a; 聚合管道 单一目的聚合方法 Map-reduce 函…...

ant design vue j-modal 修改高度

问题描述 今天在项目中遇到关于j-modal组件修改弹窗大小问题&#xff0c;我尝试使用直接使用:height"300"&#xff0c;没用效果&#xff0c;弹窗大小依然和没改之前一样&#xff0c;后来找到了这种方式可以去修改j-modal弹窗大小&#xff0c;下面来看下代码实现&…...

spring学习笔记七

一、自动装配 1.1、BookDao接口和实现类 public interface BookDao {void save(); } public class BookDaoImpl implements BookDao {public void save(){System.out.println("book dao save......");} } 1.2、BookService接口和实现类 public interface BookSer…...

hw技战法整理参考

目录 IP溯源反制 账户安全策略及预警 蜜罐部署联动方案...

uniapp 全局数据(globalData)的设置,获取,更改

globalData&#xff0c;这是一种简单的全局变量机制。这套机制在uni-app里也可以使用&#xff0c;并且全端通用 因为uniapp基本上都是将页面&#xff0c;或者页面中相同的部分&#xff0c;进行组件化&#xff0c;所以会存在父&#xff0c;子&#xff0c;&#xff08;子&#xf…...

Profinet转EtherNet/IP网关连接AB PLC的应用案例

西门子S7-1500 PLC&#xff08;profinet&#xff09;与AB PLC以太网通讯&#xff08;EtherNet/IP&#xff09;。本文主要介绍捷米特JM-EIP-PN的Profinet转EtherNet/IP网关&#xff0c;连接西门子S7-1500 PLC与AB PLC 通讯的配置过程&#xff0c;供大家参考。 1, 新建工程&…...

Python组合模式介绍、使用方法

一、Python组合模式介绍 概念&#xff1a; 组合模式(Composite Pattern)是一种结构型设计模式&#xff0c;它通过将对象组合成树状结构来表示“整体/部分”层次结构&#xff0c;让客户端可以以相同的方式处理单个对象和组合对象。 功能&#xff1a; 统一对待组合对象和叶子对…...

生成模型和判别模型工作原理介绍

您解决的大多数机器学习和深度学习问题都是从生成模型和判别模型中概念化的。在机器学习中,人们可以清楚地区分两种建模类型: 将图像分类为狗或猫属于判别性建模生成逼真的狗或猫图像是一个生成建模问题神经网络被采用得越多,生成域和判别域就增长得越多。要理解基于这些模型…...

shardingsphere读写分离配置

注&#xff1a; 如果是升级之前的单库单表&#xff0c;要将之前的 数据库接池 druid-spring-boot-starter 注释掉&#xff0c;换成 druid&#xff0c;否则无法连接数据库。 原因&#xff1a; 因为数据连接池的starter&#xff08;比如druid&#xff09;可能会先加载并且其创…...

做网站用的腾讯云服务器/长沙百度网站排名优化

你知道红木家具的面板有几种类型吗&#xff1f;你知道哪条边是大边&#xff0c;哪条边是抹头吗&#xff1f;你知道为什么传统红木家具一般不用独板制作的原因吗&#xff1f;今天941红木网小编就和大家聊聊红木家具面板小常识。大多数红木家具都有面板&#xff0c;如桌面、案面、…...

湖南长沙又检出1例阳性/关键词优化怎么弄

Linux编程点击右侧关注&#xff0c;免费入门到精通&#xff01;网友说&#xff0c;他家汪星人自从体验过滑板之后就再也不肯下地走路了。推荐↓↓↓ 长按关注?【16个技术公众号】都在这里&#xff01;涵盖&#xff1a;程序员大咖、源码共读、程序员共读、数据结构与算法、黑客…...

自己做彩票网站/小企业广告投放平台

在SharePoint 2010文档库中&#xff0c;结合单选框&#xff0c;在Ribbon中提供了批量处理文档的功能&#xff0c;比如&#xff0c;批量删除、批量签出、批量签入等&#xff0c;但是&#xff0c;很遗憾&#xff0c;没有提供批量下载&#xff0c;默认的只能一个个下载&#xff0c…...

网站建设商城/独立站建站需要多少钱

做了这么多年的数据分析和挖掘工作&#xff0c;一直都在思考一个问题&#xff0c;“互联网和金融&#xff0c;在数据挖掘上到底存在什么样的区别”。在对这个问题的摸索和理解过程中&#xff0c;发现数据挖掘本身包含很多层次。模型本身也是存在传统和时髦之分的。本文就想聊聊…...

企业网站备案在哪个部门/高端网站建设专业公司

文章目录 finallshell 推荐指数 &#xff1a; 五颗星xshell 推荐指数&#xff1a; 四颗星Putty &#xff0c;secureCRT 推荐指数&#xff1a; 三颗星MobaXterm 推荐指数&#xff1a; 四颗星Mosh 推荐指数&#xff1a; 四颗星 总结&#xff1a; 1. finallshell 推荐指数 &…...

网站根目录是哪个文件夹/网页设计制作教程

世界上最成功的人一开始是个程序员。在1974年&#xff0c;Bill Gates为Altair 8800写了一个4K的编译器&#xff0c;今天&#xff0c;他创立的Microsoft用Windows操作系统和Microsoft Office, Microsoft Home等产品统治了PC软件市场。Bill成了世界首富&#xff0c;他的个人财产今…...