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

简介: Rust vs Go:常用语法对比(十二)(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);
}
目录
相关文章
|
11天前
|
存储 Java Go
|
3天前
|
Go
go基础语法结束篇 ——函数与方法
go基础语法结束篇 ——函数与方法
|
3天前
|
编译器 Go 数据安全/隐私保护
go语言入门之路——基础语法
go语言入门之路——基础语法
|
24天前
|
Java 编译器 Go
【字节跳动青训营】后端笔记整理-1 | Go语言入门指南:基础语法和常用特性解析(一)
本文主要梳理自第六届字节跳动青训营(后端组)-Go语言原理与实践第一节(王克纯老师主讲)。
45 1
|
26天前
|
编译器 Go
Go 语言基础语法
Go 语言基础语法
23 1
|
4天前
|
存储 安全 Java
【Go语言精进之路】Go语言基础:基础语法概览
【Go语言精进之路】Go语言基础:基础语法概览
15 0
|
11天前
|
Java Go Scala
|
11天前
|
存储 Java Unix
|
24天前
|
存储 JSON Java
【字节跳动青训营】后端笔记整理-1 | Go语言入门指南:基础语法和常用特性解析(三)
在 Go 语言里,符合语言习惯的做法是使用一个单独的返回值来传递错误信息。
31 0
|
24天前
|
存储 Go C++
【字节跳动青训营】后端笔记整理-1 | Go语言入门指南:基础语法和常用特性解析(二)
Go 语言中的复合数据类型包括数组、切片(slice)、映射(map)和结构体(struct)。
45 0