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

简介: Rust vs Go:常用语法对比(12)(2)

231. Test if bytes are a valid UTF-8 string

Set b to true if the byte sequence s consists entirely of valid UTF-8 character code points, false otherwise.

测试字节是否是有效的UTF-8字符串

package main
import (
  "fmt"
  "unicode/utf8"
)
func main() {
  {
    s := []byte("Hello, 世界")
    b := utf8.Valid(s)
    fmt.Println(b)
  }
  {
    s := []byte{0xff, 0xfe, 0xfd}
    b := utf8.Valid(s)
    fmt.Println(b)
  }
}
true
false
fn main() {
    {
        let bytes = [0xc3, 0x81, 0x72, 0x76, 0xc3, 0xad, 0x7a];
        let b = std::str::from_utf8(&bytes).is_ok();
        println!("{}", b);
    }
    {
        let bytes = [0xc3, 0x81, 0x81, 0x76, 0xc3, 0xad, 0x7a];
        let b = std::str::from_utf8(&bytes).is_ok();
        println!("{}", b);
    }
}
true
false

234. Encode bytes to base64

Assign to string s the standard base64 encoding of the byte array data, as specified by RFC 4648.

将字节编码为base64

package main
import (
  "encoding/base64"
  "fmt"
)
func main() {
  data := []byte("Hello world")
  s := base64.StdEncoding.EncodeToString(data)
  fmt.Println(s)
}
//use base64;
fn main() {
    let d = "Hello, World!";
    let b64txt = base64::encode(d);
    println!("{}", b64txt);
}

235. Decode base64

Assign to byte array data the bytes represented by the base64 string s, as specified by RFC 4648.

解码base64

package main
import (
  "encoding/base64"
  "fmt"
)
func main() {
  str := "SGVsbG8gd29ybGQ="
  data, err := base64.StdEncoding.DecodeString(str)
  if err != nil {
    fmt.Println("error:", err)
    return
  }
  fmt.Printf("%q\n", data)
}
//use base64;
fn main() {
    let d = "SGVsbG8sIFdvcmxkIQ==";
    let bytes = base64::decode(d).unwrap();
    println!("Hex: {:x?}", bytes);
    println!("Txt: {}", std::str::from_utf8(&bytes).unwrap());
}
Hex: [48, 65, 6c, 6c, 6f, 2c, 20, 57, 6f, 72, 6c, 64, 21]
Txt: Hello, World!

237. Xor integers

Assign to c the result of (a xor b)

异或运算

异或整数

package main
import (
  "fmt"
)
func main() {
  a, b := 230, 42
  c := a ^ b
  fmt.Printf("a is %12b\n", a)
  fmt.Printf("b is %12b\n", b)
  fmt.Printf("c is %12b\n", c)
  fmt.Println("c ==", c)
}
a is     11100110
b is       101010
c is     11001100
c == 204

or

package main
import (
  "fmt"
  "math/big"
)
func main() {
  a, b := big.NewInt(230), big.NewInt(42)
  c := new(big.Int)
  c.Xor(a, b)
  fmt.Printf("a is %12b\n", a)
  fmt.Printf("b is %12b\n", b)
  fmt.Printf("c is %12b\n", c)
  fmt.Println("c ==", c)
}
a is     11100110
b is       101010
c is     11001100
c == 204
fn main() {
    let a = 230;
    let b = 42;
    let c = a ^ b;
    println!("{}", c);
}

238. Xor byte arrays

Write in a new byte array c the xor result of byte arrays a and b.

a and b have the same size.

异或字节数组

package main
import (
  "fmt"
)
func main() {
  a, b := []byte("Hello"), []byte("world")
  c := make([]byte, len(a))
  for i := range a {
    c[i] = a[i] ^ b[i]
  }
  fmt.Printf("a is %08b\n", a)
  fmt.Printf("b is %08b\n", b)
  fmt.Printf("c is %08b\n", c)
  fmt.Println("c ==", c)
  fmt.Printf("c as string would be %q\n", string(c))
}
a is [01001000 01100101 01101100 01101100 01101111]
b is [01110111 01101111 01110010 01101100 01100100]
c is [00111111 00001010 00011110 00000000 00001011]
c == [63 10 30 0 11]
c as string would be "?\n\x1e\x00\v"

or

package main
import (
  "fmt"
)
type T [5]byte
func main() {
  var a, b T
  copy(a[:], "Hello")
  copy(b[:], "world")
  var c T
  for i := range a {
    c[i] = a[i] ^ b[i]
  }
  fmt.Printf("a is %08b\n", a)
  fmt.Printf("b is %08b\n", b)
  fmt.Printf("c is %08b\n", c)
  fmt.Println("c ==", c)
  fmt.Printf("c as string would be %q\n", string(c[:]))
}
a is [01001000 01100101 01101100 01101100 01101111]
b is [01110111 01101111 01110010 01101100 01100100]
c is [00111111 00001010 00011110 00000000 00001011]
c == [63 10 30 0 11]
c as string would be "?\n\x1e\x00\v"
fn main() {
    let a: &[u8] = "Hello".as_bytes();
    let b: &[u8] = "world".as_bytes();
    let c: Vec<_> = a.iter().zip(b).map(|(x, y)| x ^ y).collect();
    println!("{:?}", c);
}

239. Find first regular expression match

Assign to string x the first word of string s consisting of exactly 3 digits, or the empty string if no such match exists.

A word containing more digits, or 3 digits as a substring fragment, must not match.

查找第一个正则表达式匹配项

package main
import (
  "fmt"
  "regexp"
)
func main() {
  re := regexp.MustCompile(`\b\d\d\d\b`)
  for _, s := range []string{
    "",
    "12",
    "123",
    "1234",
    "I have 12 goats, 3988 otters, 224 shrimps and 456 giraffes",
    "See p.456, for word boundaries",
  } {
    x := re.FindString(s)
    fmt.Printf("%q -> %q\n", s, x)
  }
}
"" -> ""
"12" -> ""
"123" -> "123"
"1234" -> ""
"I have 12 goats, 3988 otters, 224 shrimps and 456 giraffes" -> "224"
"See p.456, for word boundaries" -> "456"
use regex::Regex;
fn main() {
    let sentences = vec![
        "",
        "12",
        "123",
        "1234",
        "I have 12 goats, 3988 otters, 224 shrimps and 456 giraffes",
        "See p.456, for word boundaries",
    ];
    for s in sentences {
        let re = Regex::new(r"\b\d\d\d\b").expect("failed to compile regex");
        let x = re.find(s).map(|x| x.as_str()).unwrap_or("");
        println!("[{}] -> [{}]", &s, &x);
    }
}
[] -> []
[12] -> []
[123] -> [123]
[1234] -> []
[I have 12 goats, 3988 otters, 224 shrimps and 456 giraffes] -> [224]
[See p.456, for word boundaries] -> [456]

240. Sort 2 lists together

Lists a and b have the same length. Apply the same permutation to a and b to have them sorted based on the values of a.

将两个列表排序在一起.列表a和b的长度相同。对a和b应用相同的排列,根据a的值对它们进行排序。

package main
import (
  "fmt"
  "sort"
)
type K int
type T string
type sorter struct {
  k []K
  t []T
}
func (s *sorter) Len() int {
  return len(s.k)
}
func (s *sorter) Swap(i, j int) {
  // Swap affects 2 slices at once.
  s.k[i], s.k[j] = s.k[j], s.k[i]
  s.t[i], s.t[j] = s.t[j], s.t[i]
}
func (s *sorter) Less(i, j int) bool {
  return s.k[i] < s.k[j]
}
func main() {
  a := []K{9, 3, 4, 8}
  b := []T{"nine", "three", "four", "eight"}
  sort.Sort(&sorter{
    k: a,
    t: b,
  })
  fmt.Println(a)
  fmt.Println(b)
}
[3 4 8 9]
[three four eight nine]
fn main() {
    let a = vec![30, 20, 40, 10];
    let b = vec![101, 102, 103, 104];
    let mut tmp: Vec<_> = a.iter().zip(b).collect();
    tmp.as_mut_slice().sort_by_key(|(&x, _y)| x);
    let (aa, bb): (Vec<i32>, Vec<i32>) = tmp.into_iter().unzip();
    println!("{:?}, {:?}", aa, bb);
}
目录
相关文章
|
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语言入门之路——基础语法