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

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

81. Round floating point number to integer

Declare integer y and initialize it with the rounded value of floating point number x . Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).

按规则取整

package main
import (
  "fmt"
  "math"
)
func round(x float64) int {
  y := int(math.Floor(x + 0.5))
  return y
}
func main() {
  for _, x := range []float64{-1.1, -0.9, -0.5, -0.1, 0., 0.1, 0.5, 0.9, 1.1} {
    fmt.Printf("%5.1f %5d\n", x, round(x))
  }
}
 -1.1    -1
 -0.9    -1
 -0.5     0
 -0.1     0
  0.0     0
  0.1     0
  0.5     1
  0.9     1
  1.1     1
fn main() {
    let x : f64 = 2.71828;
    let y = x.round() as i64;
    println!("{} {}", x, y);
}

82. Count substring occurrences

统计子字符串出现次数

package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "Romaromamam"
  t := "mam"
  x := strings.Count(s, t)
  fmt.Println(x)
}
fn main() {
    let s = "lorem ipsum lorem ipsum lorem ipsum lorem ipsum";
    let t = "ipsum";
    let c = s.matches(t).count();
    println!("{} occurrences", c);
}

Disjoint matches: overlapping occurrences are not counted.


83. Regex with character repetition

Declare regular expression r matching strings "http", "htttp", "httttp", etc.

正则表达式匹配重复字符

package main
import (
  "fmt"
  "regexp"
)
func main() {
  r := regexp.MustCompile("htt+p")
  for _, s := range []string{
    "hp",
    "htp",
    "http",
    "htttp",
    "httttp",
    "htttttp",
    "htttttp",
    "word htttp in a sentence",
  } {
    fmt.Println(s, "=>", r.MatchString(s))
  }
}
hp => false
htp => false
http => true
htttp => true
httttp => true
htttttp => true
htttttp => true
word htttp in a sentence => true
extern crate regex;
use regex::Regex;
fn main() {
    let r = Regex::new(r"htt+p").unwrap();
    assert!(r.is_match("http"));
    assert!(r.is_match("htttp"));
    assert!(r.is_match("httttp"));
}

84. Count bits set in integer binary representation

Count number c of 1s in the integer i in base 2.

E.g. i=6 → c=2

计算十进制整型的二进制表示中 1的个数

package main
import "fmt"
func PopCountUInt64(i uint64) (c int) {
  // bit population count, see
  // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
  i -= (i >> 1) & 0x5555555555555555
  i = (i>>2)&0x3333333333333333 + i&0x3333333333333333
  i += i >> 4
  i &= 0x0f0f0f0f0f0f0f0f
  i *= 0x0101010101010101
  return int(i >> 56)
}
func PopCountUInt32(i uint32) (n int) {
  // bit population count, see
  // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
  i -= (i >> 1) & 0x55555555
  i = (i>>2)&0x33333333 + i&0x33333333
  i += i >> 4
  i &= 0x0f0f0f0f
  i *= 0x01010101
  return int(i >> 24)
}
func main() {
  for i := uint64(0); i < 16; i++ {
    c := PopCountUInt64(i)
    fmt.Printf("%4d %04[1]b %d\n", i, c)
  }
  for i := uint32(0); i < 16; i++ {
    c := PopCountUInt32(i)
    fmt.Printf("%4d %04[1]b %d\n", i, c)
  }
}
   0 0000 0
   1 0001 1
   2 0010 1
   3 0011 2
   4 0100 1
   5 0101 2
   6 0110 2
   7 0111 3
   8 1000 1
   9 1001 2
  10 1010 2
  11 1011 3
  12 1100 2
  13 1101 3
  14 1110 3
  15 1111 4
   0 0000 0
   1 0001 1
   2 0010 1
   3 0011 2
   4 0100 1
   5 0101 2
   6 0110 2
   7 0111 3
   8 1000 1
   9 1001 2
  10 1010 2
  11 1011 3
  12 1100 2
  13 1101 3
  14 1110 3
  15 1111 4

This was useful only before go 1.9. See math/bits.OnesCount instead

or

package main
import (
  "fmt"
  "math/bits"
)
func main() {
  for i := uint(0); i < 16; i++ {
    c := bits.OnesCount(i)
    fmt.Printf("%4d %04[1]b %d\n", i, c)
  }
}
   0 0000 0
   1 0001 1
   2 0010 1
   3 0011 2
   4 0100 1
   5 0101 2
   6 0110 2
   7 0111 3
   8 1000 1
   9 1001 2
  10 1010 2
  11 1011 3
  12 1100 2
  13 1101 3
  14 1110 3
  15 1111 4
fn main() {
    println!("{}", 6usize.count_ones())
}

85. Check if integer addition will overflow

检查两个整型相加是否溢出

package main
import (
  "fmt"
  "math"
)
func willAddOverflow(a, b int64) bool {
  return a > math.MaxInt64-b
}
func main() {
  fmt.Println(willAddOverflow(11111111111111111, 2))
}
fn adding_will_overflow(x: usize, y: usize) -> bool {
    x.checked_add(y).is_none()
}
fn main() {
    {
        let (x, y) = (2345678, 9012345);
        let overflow = adding_will_overflow(x, y);
        println!(
            "{} + {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
    {
        let (x, y) = (2345678901, 9012345678);
        let overflow = adding_will_overflow(x, y);
        println!(
            "{} + {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
    {
        let (x, y) = (2345678901234, 9012345678901);
        let overflow = adding_will_overflow(x, y);
        println!(
            "{} + {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
    {
        let (x, y) = (23456789012345678, 90123456789012345);
        let overflow = adding_will_overflow(x, y);
        println!(
            "{} + {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
    {
        let (x, y) = (12345678901234567890, 9012345678901234567);
        let overflow = adding_will_overflow(x, y);
        println!(
            "{} + {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
}
2345678 + 9012345 doesn't overflow
2345678901 + 9012345678 doesn't overflow
2345678901234 + 9012345678901 doesn't overflow
23456789012345678 + 90123456789012345 doesn't overflow
12345678901234567890 + 9012345678901234567 overflows

86. Check if integer multiplication will overflow

检查整型相乘是否溢出

package main
import (
  "fmt"
)
func multiplyWillOverflow(x, y uint64) bool {
  if x <= 1 || y <= 1 {
    return false
  }
  d := x * y
  return d/y != x
}
func main() {
  {
    var x, y uint64 = 2345, 6789
    if multiplyWillOverflow(x, y) {
      fmt.Println(x, "*", y, "overflows")
    } else {
      fmt.Println(x, "*", y, "doesn't overflow")
    }
  }
  {
    var x, y uint64 = 2345678, 9012345
    if multiplyWillOverflow(x, y) {
      fmt.Println(x, "*", y, "overflows")
    } else {
      fmt.Println(x, "*", y, "doesn't overflow")
    }
  }
  {
    var x, y uint64 = 2345678901, 9012345678
    if multiplyWillOverflow(x, y) {
      fmt.Println(x, "*", y, "overflows")
    } else {
      fmt.Println(x, "*", y, "doesn't overflow")
    }
  }
}
2345 * 6789 doesn't overflow
2345678 * 9012345 doesn't overflow
2345678901 * 9012345678 overflows
fn main() {
    {
        let (x, y) = (2345, 6789);
        let overflow = multiply_will_overflow(x, y);
        println!(
            "{} * {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
    {
        let (x, y) = (2345678, 9012345);
        let overflow = multiply_will_overflow(x, y);
        println!(
            "{} * {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
    {
        let (x, y) = (2345678901, 9012345678);
        let overflow = multiply_will_overflow(x, y);
        println!(
            "{} * {} {}",
            x,
            y,
            if overflow {
                "overflows"
            } else {
                "doesn't overflow"
            }
        );
    }
}
fn multiply_will_overflow(x: i64, y: i64) -> bool {
    x.checked_mul(y).is_none()
}
2345 * 6789 doesn't overflow
2345678 * 9012345 doesn't overflow
2345678901 * 9012345678 overflows

87. Stop program

Exit immediatly.

If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.

停止程序,立即退出。

package main
import "os"
func main() {
  os.Exit(1)
  print(2222)
}
fn main() {
    std::process::exit(1);
    println!("42");
}

88. Allocate 1M bytes

分配1M内存

package main
import "fmt"
func main() {
  buf := make([]byte, 1000000)
  for i, b := range buf {
    if b != 0 {
      fmt.Println("Found unexpected value", b, "at position", i)
    }
  }
  fmt.Println("Buffer was correctly initialized with zero values.")
}
fn main() {
    let buf: Vec<u8> = Vec::with_capacity(1024 * 1024);
    println!("{:?}", buf.capacity());
}

89. Handle invalid argument

处理无效参数

package main
import "fmt"
// NewSquareMatrix creates a N-by-N matrix
func NewSquareMatrix(N int) ([][]float64, error) {
  if N < 0 {
    return nil, fmt.Errorf("Invalid size %d: order cannot be negative", N)
  }
  matrix := make([][]float64, N)
  for i := range matrix {
    matrix[i] = make([]float64, N)
  }
  return matrix, nil
}
func main() {
  N1 := 3
  matrix1, err1 := NewSquareMatrix(N1)
  if err1 == nil {
    fmt.Println(matrix1)
  } else {
    fmt.Println(err1)
  }
  N2 := -2
  matrix2, err2 := NewSquareMatrix(N2)
  if err2 == nil {
    fmt.Println(matrix2)
  } else {
    fmt.Println(err2)
  }
}
[[0 0 0] [0 0 0] [0 0 0]]
Invalid size -2: order cannot be negative
#[derive(Debug, PartialEq, Eq)]
enum CustomError { InvalidAnswer }
fn do_stuff(x: i32) -> Result<i32, CustomError> {
    if x != 42 {
%2

90. Read-only outside

外部只读

type Foo struct {
  x int
}
func (f *Foo) X() int {
  return f.x
}
x is private, because it is not capitalized.
(*Foo).X is a public getter (a read accessor).
struct Foo {
    x: usize
}
impl Foo {
    pub fn new(x: usize) -> Self {
        Foo { x }
    }
    pub fn x<'a>(&'a self) -> &'a usize {
        &self.x
    }
}


目录
相关文章
|
17天前
|
Rust API
【Rust学习】09_方法语法
结构体让你可以创建出在你的领域中有意义的自定义类型。通过结构体,我们可以将相关联的数据片段联系起来并命名它们,这样可以使得代码更加清晰。在 impl 块中,你可以定义与你的类型相关联的函数,而方法是一种相关联的函数,允许您指定结构体的实例具有的行为。 但是结构体并不是创建自定义类型的唯一方式:让我们转向 Rust 的 enum 功能,将另一个工具添加到你的工具箱中。
10 0
|
28天前
|
Java 编译器 Go
Go to Learn Go之基础语法
Go to Learn Go之基础语法
16 0
|
2月前
|
Rust 安全 编译器
30天拿下Rust之语法大全
Rust是一种系统级编程语言,以其独特的所有权系统和内存安全性受到开发者青睐。本文从基本数据类型入手,介绍了标量类型如整数、浮点数、布尔值及字符,复合类型如元组、数组和结构体等。此外,还探讨了变量与常量的声明与使用,条件判断与循环语句的语法,以及函数定义与调用的方法。文章通过示例代码展示了如何使用Rust编写简洁高效的程序,并简要介绍了注释与宏的概念,为读者快速掌握这门语言提供了实用指南。欲获取最新文章或交流技术问题,请关注微信公众号“希望睿智”。
39 1
|
1月前
|
Rust Linux Go
Rust/Go语言学习
Rust/Go语言学习
|
4月前
|
存储 Java Go
|
3月前
|
Rust
Rust 中使用 :: 这种语法的几种情况
Rust 中使用 :: 这种语法的几种情况
|
4月前
|
Rust
Rust的if let语法:更简洁的模式匹配
Rust的if let语法:更简洁的模式匹配
|
4月前
|
编译器 Go 开发者
|
4月前
|
Go
go基础语法结束篇 ——函数与方法
go基础语法结束篇 ——函数与方法
|
4月前
|
编译器 Go 数据安全/隐私保护
go语言入门之路——基础语法
go语言入门之路——基础语法