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);
}
目录
相关文章
|
2天前
|
安全 Java Go
Java vs. Go:并发之争
【4月更文挑战第20天】
23 1
|
2天前
|
Rust 安全 程序员
|
2天前
|
算法 Java Go
Go vs Java:内存管理与垃圾回收机制对比
对比了Go和Java的内存管理与垃圾回收机制。Java依赖JVM自动管理内存,使用堆栈内存并采用多种垃圾回收算法,如标记-清除和分代收集。Go则提供更多的手动控制,内存分配与释放由分配器和垃圾回收器协同完成,使用三色标记算法并发回收。示例展示了Java中对象自动创建和销毁,而Go中开发者需注意内存泄漏。选择语言应根据项目需求和技术栈来决定。
|
2天前
|
Java Linux Go
一文带你速通Go语言基础语法
本文是关于Go语言的入门介绍,作者因其简洁高效的特性对Go语言情有独钟。文章首先概述了Go语言的优势,包括快速上手、并发编程简单、设计简洁且功能强大,以及丰富的标准库。接着,文章通过示例展示了如何编写和运行Go代码,包括声明包、导入包和输出语句。此外,还介绍了Go的语法基础,如变量类型(数字、字符串、布尔和复数)、变量赋值、类型转换和默认值。文章还涉及条件分支(if和switch)和循环结构(for)。最后,简要提到了Go函数的定义和多返回值特性,以及一些常见的Go命令。作者计划在后续文章中进一步探讨Go语言的其他方面。
13 0
|
2天前
|
Java Go 云计算
【Go语言专栏】Go语言语法基础详解
【4月更文挑战第30天】Go语言,因简洁、高效和并发处理能力深受开发者喜爱,尤其在云计算和微服务领域广泛应用。本文为初学者详解Go语法基础,包括静态类型、垃圾回收、并发编程、错误处理和包管理。通过学习,读者将理解Go语言设计哲学,掌握其语法,以提升开发效率。Go的并发核心是协程和通道,而错误处理采用显式方式,增强了代码的健壮性。Go的包管理机制支持模块化开发。了解这些基础,将助你更好地探索Go语言的世界及其未来潜力。
|
2天前
|
Java 大数据 Go
Go vs Java:在大数据处理领域的性能对比
Go与Java在大数据处理中各有特点。Go启动快,内存占用少,静态类型及并发模型(goroutine和channel)使其在并发性能上有优势。Java虽然启动慢,JVM内存占用高,但拥有丰富的生态系统和并发工具。代码示例展示了Go的goroutine和Java的线程池处理大数据的场景。在性能上,Go可能更优,但Java的跨平台性和生态广度使其仍被广泛应用。
|
2天前
|
Go
Golang深入浅出之-Go语言基础语法:变量声明与赋值
【4月更文挑战第20天】本文介绍了Go语言中变量声明与赋值的基础知识,包括使用`var`关键字和简短声明`:=`的方式,以及多变量声明与赋值。强调了变量作用域、遮蔽、初始化与零值的重要性,并提醒读者注意类型推断时的一致性。了解这些概念有助于避免常见错误,提高编程技能和面试表现。
27 0
|
2天前
|
Rust 安全 程序员
Rust vs Go:解析两者的独特特性和适用场景
在讨论 Rust 与 Go 两种编程语言哪种更优秀时,我们将探讨它们在性能、简易性、安全性、功能、规模和并发处理等方面的比较。同时,我们看看它们有什么共同点和根本的差异。现在就来看看这个友好而公平的对比。
|
2天前
|
Rust C++
Rust那些事之Borrow VS AsRef?
【4月更文挑战第3天】Rust中的Borrow和AsRef是相似的trait,都提供了一个方法来获取引用。Borrow需要借用值的Hash、Eq和Ord与拥有值相等,适合结构体的单字段借用;而AsRef无此限制,有默认实现,可接受引用或值。当需要特殊trait一致性时(如HashMap的键值比较),使用Borrow;当仅需简单引用转换时,使用AsRef。
34 0
|
9月前
|
Rust Go C++
Rust vs Go:常用语法对比(十三)(1)
Rust vs Go:常用语法对比(十三)(1)
64 0
http://www.vxiaotou.com