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

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

image.png

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



目录
相关文章
|
4月前
|
安全 Java Go
Java vs. Go:并发之争
【4月更文挑战第20天】
130 1
|
4月前
|
Rust 安全 程序员
|
4月前
|
算法 Java Go
Go vs Java:内存管理与垃圾回收机制对比
对比了Go和Java的内存管理与垃圾回收机制。Java依赖JVM自动管理内存,使用堆栈内存并采用多种垃圾回收算法,如标记-清除和分代收集。Go则提供更多的手动控制,内存分配与释放由分配器和垃圾回收器协同完成,使用三色标记算法并发回收。示例展示了Java中对象自动创建和销毁,而Go中开发者需注意内存泄漏。选择语言应根据项目需求和技术栈来决定。
|
25天前
|
Rust 安全 编译器
30天拿下Rust之语法大全
Rust是一种系统级编程语言,以其独特的所有权系统和内存安全性受到开发者青睐。本文从基本数据类型入手,介绍了标量类型如整数、浮点数、布尔值及字符,复合类型如元组、数组和结构体等。此外,还探讨了变量与常量的声明与使用,条件判断与循环语句的语法,以及函数定义与调用的方法。文章通过示例代码展示了如何使用Rust编写简洁高效的程序,并简要介绍了注释与宏的概念,为读者快速掌握这门语言提供了实用指南。欲获取最新文章或交流技术问题,请关注微信公众号“希望睿智”。
33 1
|
10天前
|
Rust Linux Go
Rust/Go语言学习
Rust/Go语言学习
|
2月前
|
Rust
Rust 中使用 :: 这种语法的几种情况
Rust 中使用 :: 这种语法的几种情况
|
3月前
|
Rust
Rust的if let语法:更简洁的模式匹配
Rust的if let语法:更简洁的模式匹配
|
4月前
|
Rust 安全 Java
Rust 和 Go:如何选择最适合你的编程语言
Rust 和 Go 都是优秀的选择 首先,重要的是要说 Rust 和 Go 都是非常优秀的编程语言。它们都是现代的、强大的,被广泛采用,且提供了卓越的性能。
57 1
|
4月前
|
设计模式 Rust Java
【一起学Rust | 设计模式】习惯语法——默认特质、集合智能指针、析构函数
【一起学Rust | 设计模式】习惯语法——默认特质、集合智能指针、析构函数
81 0
|
4月前
|
Java 大数据 Go
Go vs Java:在大数据处理领域的性能对比
Go与Java在大数据处理中各有特点。Go启动快,内存占用少,静态类型及并发模型(goroutine和channel)使其在并发性能上有优势。Java虽然启动慢,JVM内存占用高,但拥有丰富的生态系统和并发工具。代码示例展示了Go的goroutine和Java的线程池处理大数据的场景。在性能上,Go可能更优,但Java的跨平台性和生态广度使其仍被广泛应用。