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

题图来自 Go vs. Rust performance comparison: The basics
61. Get current date
获取当前时间
package main
import (
"fmt"
"time"
)
func main() {
d := time.Now()
fmt.Println("Now is", d)
// The Playground has a special sandbox, so you may get a Time value fixed in the past.
}
Now is 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
extern crate time;
let d = time::now();
or
use std::time::SystemTime;
fn main() {
let d = SystemTime::now();
println!("{:?}", d);
}
SystemTime { tv_sec: 1526318418, tv_nsec: 699329521 }
62. Find substring position
字符串查找
查找子字符串位置
package main
import (
"fmt"
"strings"
)
func main() {
x := "été chaud"
{
y := "chaud"
i := strings.Index(x, y)
fmt.Println(i)
}
{
y := "froid"
i := strings.Index(x, y)
fmt.Println(i)
}
}
i is the byte index of y in x, not the character (rune) index. i will be -1 if y is not found in x.
6
-1
fn main() {
let x = "été chaud";
let y = "chaud";
let i = x.find(y);
println!("{:?}", i);
let y = "froid";
let i = x.find(y);
println!("{:?}", i);
}
Some(6)
None
63. Replace fragment of a string
替换字符串片段
package main
import (
"fmt"
"strings"
)
func main() {
x := "oink oink oink"
y := "oink"
z := "moo"
x2 := strings.Replace(x, y, z, -1)
fmt.Println(x2)
}
moo moo moo
fn main() {
let x = "lorem ipsum dolor lorem ipsum";
let y = "lorem";
let z = "LOREM";
let x2 = x.replace(&y, &z);
println!("{}", x2);
}
LOREM ipsum dolor LOREM ipsum
64. Big integer : value 3 power 247
超大整数
package main
import "fmt"
import "math/big"
func main() {
x := new(big.Int)
x.Exp(big.NewInt(3), big.NewInt(247), nil)
fmt.Println(x)
}
7062361041362837614435796717454722507454089864783271756927542774477268334591598635421519542453366332460075473278915787
extern crate num;
use num::bigint::ToBigInt;
fn main() {
let a = 3.to_bigint().unwrap();
let x = num::pow(a, 247);
println!("{}", x)
}
7062361041362837614435796717454722507454089864783271756927542774477268334591598635421519542453366332460075473278915787
65. Format decimal number
格式化十进制数
package main
import "fmt"
func main() {
x := 0.15625
s := fmt.Sprintf("%.1f%%", 100.0*x)
fmt.Println(s)
}
15.6%
fn main() {
let x = 0.15625f64;
let s = format!("{:.1}%", 100.0 * x);
println!("{}", s);
}
15.6%
66. Big integer exponentiation
大整数幂运算
package main
import "fmt"
import "math/big"
func exp(x *big.Int, n int) *big.Int {
nb := big.NewInt(int64(n))
var z big.Int
z.Exp(x, nb, nil)
return &z
}
func main() {
x := big.NewInt(3)
n := 5
z := exp(x, n)
fmt.Println(z)
}
243
extern crate num;
use num::bigint::BigInt;
fn main() {
let x = BigInt::parse_bytes(b"600000000000", 10).unwrap();
let n = 42%
67. Binomial coefficient "n choose k"
Calculate binom(n, k) = n! / (k! * (n-k)!). Use an integer type able to handle huge numbers.
二项式系数“n选择k”
package main
import (
"fmt"
"math/big"
)
func main() {
z := new(big.Int)
z.Binomial(4, 2)
fmt.Println(z)
z.Binomial(133, 71)
fmt.Println(z)
}
6
555687036928510235891585199545206017600
extern crate num;
use num::bigint::BigInt;
use num::bigint::ToBigInt;
use num::traits::One;
fn binom(n: u64, k: u64) -> BigInt {
let mut res = BigInt::one();
for i in 0..k {
res = (res * (n - i).to_bigint().unwrap()) /
(i + 1).to_bigint().unwrap();
}
res
}
fn main() {
let n = 133;
let k = 71;
println!("{}", binom(n, k));
}
555687036928510235891585199545206017600
68. Create a bitset
创建位集合
package main
import (
"fmt"
"math/big"
)
func main() {
var x *big.Int = new(big.Int)
x.SetBit(x, 42, 1)
for _, y := range []int{13, 42} {
fmt.Println("x has bit", y, "set to", x.Bit(y))
}
}
x has bit 13 set to 0
x has bit 42 set to 1
or
package main
import (
"fmt"
)
const n = 1024
func main() {
x := make([]bool, n)
x[42] = true
for _, y := range []int{13, 42} {
fmt.Println("x has bit", y, "set to", x[y])
}
}
x has bit 13 set to false
x has bit 42 set to true
or
package main
import (
"fmt"
)
func main() {
const n = 1024
x := NewBitset(n)
x.SetBit(13)
x.SetBit(42)
x.ClearBit(13)
for _, y := range []int{13, 42} {
fmt.Println("x has bit", y, "set to", x.GetBit(y))
}
}
type Bitset []uint64
func NewBitset(n int) Bitset {
return make(Bitset, (n+63)/64)
}
func (b Bitset) GetBit(index int) bool {
pos := index / 64
j := index % 64
return (b[pos] & (uint64(1) << j)) != 0
}
func (b Bitset) SetBit(index int) {
pos := index / 64
j := index % 64
b[pos] |= (uint64(1) << j)
}
func (b Bitset) ClearBit(index int) {
pos := index / 64
j := index % 64
b[pos] ^= (uint64(1) << j)
}
x has bit 13 set to false
x has bit 42 set to true
fn main() {
let n = 20;
let mut x = vec![false; n];
x[3] = true;
println!("{:?}", x);
}
[false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]
69. Seed random generator
Use seed s to initialize a random generator.
If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
随机种子生成器
package main
import (
"fmt"
"math/rand"
)
func main() {
var s int64 = 42
rand.Seed(s)
fmt.Println(rand.Int())
}
3440579354231278675
or
package main
import (
"fmt"
"math/rand"
)
func main() {
var s int64 = 42
r := rand.New(rand.NewSource(s))
fmt.Println(r.Int())
}
3440579354231278675
use rand::{Rng, SeedableRng, rngs::StdRng};
fn main() {
let s = 32;
let mut rng = StdRng::seed_from_u64(s);
println!("{:?}", rng.gen::<f32>());
}
0.35038823
70. Use clock as random generator seed
Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.
使用时钟作为随机生成器的种子
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
// Well, the playground date is actually fixed in the past, and the
// output is cached.
// But if you run this on your workstation, the output will vary.
fmt.Println(rand.Intn(999))
}
524
or
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// Well, the playground date is actually fixed in the past, and the
// output is cached.
// But if you run this on your workstation, the output will vary.
fmt.Println(r.Intn(999))
}
524
use rand::{Rng, SeedableRng, rngs::StdRng};
use std::time::SystemTime;
fn main() {
let d = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Duration since UNIX_EPOCH failed");
let mut rng = StdRng::seed_from_u64(d.as_secs());
println!("{:?}", rng.gen::<f32>());
}
0.7326781
71. Echo program implementation
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
实现 Echo 程序
package main
import "fmt"
import "os"
import "strings"
func main() {
fmt.Println(strings.Join(os.Args[1:], " "))
}
use std::env;
fn main() {
println!("{}", env::args().skip(1).collect::<Vec<_>>().join(" "));
}
or
use itertools::Itertools;
println!("{}", std::env::args().skip(1).format(" "));
74. Compute GCD
Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.
计算大整数a和b的最大公约数x。使用能够处理大数的整数类型。
package main
import "fmt"
import "math/big"
func main() {
a, b, x := new(big.Int), new(big.Int), new(big.Int)
a.SetString("6000000000000", 10)
b.SetString("9000000000000", 10)
x.GCD(nil, nil, a, b)
fmt.Println(x)
}
3000000000000
extern crate num;
use num::Integer;
use num::bigint::BigInt;
fn main() {
let a = BigInt::parse_bytes(b"6000000000000", 10).unwrap();
let b = BigInt::parse_bytes(b"9000000000000", 10).unwrap();
let x = a.gcd(&b);
println!("{}", x);
}
3000000000000
75. Compute LCM
计算大整数a和b的最小公倍数x。使用能够处理大数的整数类型。
Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.
package main
import "fmt"
import "math/big"
func main() {
a, b, gcd, x := new(big.Int), new(big.Int), new(big.Int), new(big.Int)
a.SetString("6000000000000", 10)
b.SetString("9000000000000", 10)
gcd.GCD(nil, nil, a, b)
x.Div(a, gcd).Mul(x, b)
fmt.Println(x)
}
18000000000000
extern crate num;
use num::bigint::BigInt;
use num::Integer;
fn main() {
let a = BigInt::parse_bytes(b"6000000000000", 10).unwrap();
let b = BigInt::parse_bytes(b"9000000000000", 10).unwrap();
let x = a.lcm(&b);
println!("x = {}", x);
}
x = 18000000000000
76. Binary digits from an integer
Create the string s of integer x written in base 2.
E.g. 13 -> "1101"
将十进制整数转换为二进制数字
package main
import "fmt"
import "strconv"
func main() {
x := int64(13)
s := strconv.FormatInt(x, 2)
fmt.Println(s)
}
1101
or
package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(13)
s := fmt.Sprintf("%b", x)
fmt.Println(s)
}
1101
fn main() {
let x = 13;
let s = format!("{:b}", x);
println!("{}", s);
}
1101
77. SComplex number
Declare a complex x and initialize it with value (3i - 2). Then multiply it by i.
复数
package main
import (
"fmt"
"reflect"
)
func main() {
x := 3i - 2
x *= 1i
fmt.Println(x)
fmt.Print(reflect.TypeOf(x))
}
(-3-2i)
complex128
extern crate num;
use num::Complex;
fn main() {
let mut x = Complex::new(-2, 3);
x *= Complex::i();
println!("{}", x);
}
-3-2i
78. "do while" loop
Execute a block once, then execute it again as long as boolean condition c is true.
循环执行
package main
import (
"fmt"
"math/rand"
)
func main() {
for {
x := rollDice()
fmt.Println("Got", x)
if x == 3 {
break
}
}
}
func rollDice() int {
return 1 + rand.Intn(6)
}
Go has no do while loop, use the for loop, instead.
Got 6
Got 4
Got 6
Got 6
Got 2
Got 1
Got 2
Got 3
or
package main
import (
"fmt"
"math/rand"
)
func main() {
for done := false; !done; {
x := rollDice()
fmt.Println("Got", x)
done = x == 3
}
}
func rollDice() int {
return 1 + rand.Intn(6)
}
Got 6
Got 4
Got 6
Got 6
Got 2
Got 1
Got 2
Got 3
loop {
doStuff();
if !c { break; }
}
Rust has no do-while loop with syntax sugar. Use loop and break.
79. Convert integer to floating point number
Declare floating point number y and initialize it with the value of integer x .
整型转浮点型
声明浮点数y并用整数x的值初始化它。
package main
import (
"fmt"
"reflect"
)
func main() {
x := 5
y := float64(x)
fmt.Println(y)
fmt.Printf("%.2f\n", y)
fmt.Println(reflect.TypeOf(y))
}
5
5.00
float64
fn main() {
let i = 5;
let f = i as f64;
println!("int {:?}, float {:?}", i, f);
}
int 5, float 5.0
80. Truncate floating point number to integer
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x . Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
浮点型转整型
package main
import "fmt"
func main() {
a := -6.4
b := 6.4
c := 6.6
fmt.Println(int(a))
fmt.Println(int(b))
fmt.Println(int(c))
}
-6
6
6
fn main() {
let x = 41.59999999f64;
let y = x as i32;
println!("{}", y);
}
41
本文由 mdnice 多平台发布
相关文章:

Rust vs Go:常用语法对比(四)
题图来自 Go vs. Rust performance comparison: The basics 61. Get current date 获取当前时间 package mainimport ( "fmt" "time")func main() { d : time.Now() fmt.Println("Now is", d) // The Playground has a special sandbox, so you …...
c++ 派生类 文本查询程序再探
Query_base类和Query类 //这是一个抽象基类,具体的查询类型从中派生,所有成员都是private的 class Query_base {friend class Query;protected:using line_no TextQuery::line_no;//用于level函数virtual ~Query_base() default;private://eval返回与…...

17. 电话号码的字母组合
题目描述 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 示例 1: 输入:digits "23" …...

Redis 基础知识和核心概念解析:理解 Redis 的键值操作和过期策略
🌷🍁 博主 libin9iOak带您 Go to New World.✨🍁 🦄 个人主页——libin9iOak的博客🎐 🐳 《面试题大全》 文章图文并茂🦕生动形象🦖简单易学!欢迎大家来踩踩~ἳ…...

Jenkins中sh函数的用法
在Jenkins的Pipeline中,sh函数的用法 用法一 单个命令字符串包括使用,示例如下: sh echo "Hello, Jenkins!"用法二 多个命令字符串包括命令列表使用,示例如下: sh echo "Step 1" echo "…...

Android 之 Canvas API 详解 (Part 3) Matrix 和 drawBitmapMesh
本节引言: 在Canvas的API文档中,我们看到这样一个方法:drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) 这个Matrix可是有大文章的,前面我们在学Paint的API中的ColorFilter中曾讲过ColorMatrix 颜色矩阵,一个4…...

基于Ubuntu 22.04 编译chip-tool工具
前言 编译过程有点曲折,做下记录,过程中,有参考别人写的博客,也看github 官方介绍,终于跑通了~ 环境说明: 首先需要稳定的梯子,可以访问“外网”ubuntu 环境,最终成功实验在Ubunt…...

opencv-17 脸部打码及解码
使用掩模和按位运算方式实现的对脸部打码、解码实例 代码如下: import cv2 import numpy as np #读取原始载体图像 lenacv2.imread("lena.png",0) #读取原始载体图像的 shape 值 r,clena.shape masknp.zeros((r,c),dtypenp.uint8) mask[220:400,250:350…...
JVM分享
JVM分享 官网:https://docs.oracle.com/javase/specs/jvms/se8/html/index.html Java代码的执行流程 我们编写完之后的java文件如果要运行,java文件会编译成class文件,在jvm中运行时ClassLoader会加载class文件,加载进来之后&a…...

Apache Dubbo CVE-2021-36162 挖掘过程
01 漏洞背景 发现该漏洞的起因是在分析 CVE-2021-30181 的脚本注入补丁的时候,意外发现了几个已被修复的 yaml 反序列化漏洞,还以为是未公开的Nday,查询后发现其实对应的是 CVE-2021-30180 漏洞的修复代码。通过查看补丁可以知道,…...
开源框架面试题目整理
目录 SpringIOC SpringAOP Spring的生命周期 Spring Bean作用域 Spring Bean作用域并发安全 Spring循环依赖...

Mr. Cappuccino的第52杯咖啡——Mybatis环境搭建与使用
Mybatis环境搭建与使用 Mybatis介绍Mybatis环境搭建与使用基于XML方式-原生方式开发创建数据库表项目准备项目结构项目代码实体类中添加有参构造方法产生的问题 基于XML方式-mapper代理开发项目准备项目结构项目代码SQL映射文件中namespace未设置为接口全限定名产生的问题 基于…...

了解Unity编辑器之组件篇Tilemap(五)
Tilemap:用于创建和编辑2D网格地图的工具。Tilemap的主要作用是简化2D游戏中地图的创建、编辑和渲染过程。以下是一些Tilemap的主要用途: 2D地图绘制:Tilemap提供了一个可视化的编辑器界面,可以快速绘制2D地图,例如迷…...
Linux字符设备操作函数
Linux字符设备操作函数是指对字符设备进行打开、关闭、读取、写入、控制等基本操作的函数,它们通过字符设备结构体中的 file_operations 结构体来定义。常用的字符设备操作函数包括: 1、open: 当一个进程试图打开设备文件时,调用这个函数。开…...

吉林大学计算机软件考研经验贴
文章目录 简介政治英语数学专业课 简介 本人23考研,一战上岸吉林大学软件工程专硕,政治72分,英一71分,数二144分,专业课967综合146分,总分433分,上图: 如果学弟学妹需要专业课资料…...
2023-07-26力扣每日一题-区间翻转线段树
链接: 2569. 更新数组后处理求和查询 题意: 给两个等长数组nums1和nums2,三个操作: 操作1:将nums1的[l,r]翻转(0变1,1变0) 操作2:将nums2[any]变成nums2[any]nums1[any]*p&…...
Java设计模式之 -- 桥接模式
什么是桥接模式 桥接模式是一种结构型设计模式,也被称为“Handle/Body”。这种设计模式主要用于将抽象部分与它的实现部分分离,使它们可以独立地变化。这种方式有助于减少系统中的耦合性,增加了扩展性。 主要解决什么问题 桥接模式主要解决…...
【node.js】02-path模块
目录 1. path.join() 2. path.basename() 3. path.extname() 1. path.join() 使用 path.join() 方法,可以把多个路径片段拼接为完整的路径字符串,语法格式如下: path.join([...paths]) 例子: const path require(path)co…...

攻防世界-Reverse-re1
题目描述:菜鸡开始学习逆向工程,首先是最简单的题目 下载附件,执行程序,如下界面 1. 思路分析 没啥说的,既然题目都说是一道简单的逆向题,那么直接使用ida逆向即可,看逆向出的结果是否能写入到…...
AES加密的基本常识和封装类
AES加密的基本常识和封装类 AES(Advanced Encryption Standard)是一种对称密钥加密算法,被广泛用于保护敏感数据的安全性。它是一种块加密算法,意味着它将明文数据分成固定大小的块,并使用相同的密钥对每个块进行独立…...

IDEA运行Tomcat出现乱码问题解决汇总
最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…...

中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试
作者:Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位:中南大学地球科学与信息物理学院论文标题:BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接:https://arxiv.…...
【磁盘】每天掌握一个Linux命令 - iostat
目录 【磁盘】每天掌握一个Linux命令 - iostat工具概述安装方式核心功能基础用法进阶操作实战案例面试题场景生产场景 注意事项 【磁盘】每天掌握一个Linux命令 - iostat 工具概述 iostat(I/O Statistics)是Linux系统下用于监视系统输入输出设备和CPU使…...

智能在线客服平台:数字化时代企业连接用户的 AI 中枢
随着互联网技术的飞速发展,消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁,不仅优化了客户体验,还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用,并…...
使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装
以下是基于 vant-ui(适配 Vue2 版本 )实现截图中照片上传预览、删除功能,并封装成可复用组件的完整代码,包含样式和逻辑实现,可直接在 Vue2 项目中使用: 1. 封装的图片上传组件 ImageUploader.vue <te…...

Java-41 深入浅出 Spring - 声明式事务的支持 事务配置 XML模式 XML+注解模式
点一下关注吧!!!非常感谢!!持续更新!!! 🚀 AI篇持续更新中!(长期更新) 目前2025年06月05日更新到: AI炼丹日志-28 - Aud…...
AI编程--插件对比分析:CodeRider、GitHub Copilot及其他
AI编程插件对比分析:CodeRider、GitHub Copilot及其他 随着人工智能技术的快速发展,AI编程插件已成为提升开发者生产力的重要工具。CodeRider和GitHub Copilot作为市场上的领先者,分别以其独特的特性和生态系统吸引了大量开发者。本文将从功…...
今日学习:Spring线程池|并发修改异常|链路丢失|登录续期|VIP过期策略|数值类缓存
文章目录 优雅版线程池ThreadPoolTaskExecutor和ThreadPoolTaskExecutor的装饰器并发修改异常并发修改异常简介实现机制设计原因及意义 使用线程池造成的链路丢失问题线程池导致的链路丢失问题发生原因 常见解决方法更好的解决方法设计精妙之处 登录续期登录续期常见实现方式特…...
2023赣州旅游投资集团
单选题 1.“不登高山,不知天之高也;不临深溪,不知地之厚也。”这句话说明_____。 A、人的意识具有创造性 B、人的认识是独立于实践之外的 C、实践在认识过程中具有决定作用 D、人的一切知识都是从直接经验中获得的 参考答案: C 本题解…...

人工智能(大型语言模型 LLMs)对不同学科的影响以及由此产生的新学习方式
今天是关于AI如何在教学中增强学生的学习体验,我把重要信息标红了。人文学科的价值被低估了 ⬇️ 转型与必要性 人工智能正在深刻地改变教育,这并非炒作,而是已经发生的巨大变革。教育机构和教育者不能忽视它,试图简单地禁止学生使…...