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

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

131. Successive conditions

Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true. Don't evaluate a condition when a previous condition was true.

连续条件判等

package main
import (
  "fmt"
  "strings"
)
func conditional(x string) {
  switch {
  case c1(x):
    f1()
  case c2(x):
    f2()
  case c3(x):
    f3()
  }
}
func main() {
  conditional("dog Snoopy")
  conditional("fruit Raspberry")
}
func f1() {
  fmt.Println("I'm a Human")
}
func f2() {
  fmt.Println("I'm a Dog")
}
func f3() {
  fmt.Println("I'm a Fruit")
}
var c1, c2, c3 = prefixCheck("human"), prefixCheck("dog"), prefixCheck("fruit")
func prefixCheck(prefix string) func(string) bool {
  return func(x string) bool {
    return strings.HasPrefix(x, prefix)
  }
}
I'm a Dog
I'm a Fruit
if c1 { f1() } else if c2 { f2() } else if c3 { f3() }

or

match true {
    _ if c1 => f1(),
    _ if c2 => f2(),
    _ if c3 => f3(),
    _ => (),
}

132. Measure duration of procedure execution

Run procedure f, and return the duration of the execution of f.

度量程序执行时间

package main
import (
  "fmt"
  "regexp"
  "strings"
  "time"
)
func clock(f func()) time.Duration {
  t := time.Now()
  f()
  return time.Since(t)
}
func f() {
  re := regexp.MustCompilePOSIX("|A+{300}")
  re.FindAllString(strings.Repeat("A", 299), -1)
}
func main() {
  d := clock(f)
  // The result is always zero in the playground, which has a fixed clock!
  // Try it on your workstation instead.
  fmt.Println(d)
}
use std::time::Instant;
let start = Instant::now();
f();
let duration = start.elapsed();

133. Case-insensitive string contains

Set boolean ok to true if string word is contained in string s as a substring, even if the case doesn't match, or to false otherwise.

不区分大小写的字符串包含

package main
import (
  "fmt"
  "strings"
)
// Package _strings has no case-insensitive version of _Contains, so
// we have to make our own.
func containsCaseInsensitive(s, word string) bool {
  lowerS, lowerWord := strings.ToLower(s), strings.ToLower(word)
  ok := strings.Contains(lowerS, lowerWord)
  return ok
}
func main() {
  s := "Let's dance the macarena"
  word := "Dance"
  ok := containsCaseInsensitive(s, word)
  fmt.Println(ok)
  word = "dance"
  ok = containsCaseInsensitive(s, word)
  fmt.Println(ok)
  word = "Duck"
  ok = containsCaseInsensitive(s, word)
  fmt.Println(ok)
}
true
true
false
extern crate regex;
use regex::Regex;
fn main() {
    let s = "Let's dance the macarena";
    {
        let word = "Dance";
        let re = Regex::new(&format!("(?i){}", regex::escape(word))).unwrap();
        let ok = re.is_match(&s);
        println!("{}", ok);
    }
    {
        let word = "dance";
        let re = Regex::new(&format!("(?i){}", regex::escape(word))).unwrap();
        let ok = re.is_match(&s);
        println!("{}", ok);
    }
    {
        let word = "Duck";
        let re = Regex::new(&format!("(?i){}", regex::escape(word))).unwrap();
        let ok = re.is_match(&s);
        println!("{}", ok);
    }
}
true
true
false

or

use regex::RegexBuilder;
fn main() {
    let s = "FooBar";
    let word = "foo";
    let re = RegexBuilder::new(&regex::escape(word))
        .case_insensitive(true)
        .build()
        .unwrap();
    let ok = re.is_match(s);
    println!("{:?}", ok);
}

or

fn main() {
    let s = "Let's dance the macarena";
    {
        let word = "Dance";
        let ok = s.to_ascii_lowercase().contains(&word.to_ascii_lowercase());
        println!("{}", ok);
    }
    {
        let word = "dance";
        let ok = s.to_ascii_lowercase().contains(&word.to_ascii_lowercase());
        println!("{}", ok);
    }
    {
        let word = "Duck";
        let ok = s.to_ascii_lowercase().contains(&word.to_ascii_lowercase());
        println!("{}", ok);
    }
}
true
true
false

134. Create a new list

创建一个新list

package main
import (
  "fmt"
)
func main() {
  var a, b, c T = "This", "is", "wonderful"
  items := []T{a, b, c}
  fmt.Println(items)
}
type T string
fn main() {
    let (a, b, c) = (11, 22, 33);
    let items = vec![a, b, c];
    println!("{:?}", items);
}

135. Remove item from list, by its value

Remove at most 1 item from list items, having value x. This will alter the original list or return a new list, depending on which is more idiomatic. If there are several occurrences of x in items, remove only one of them. If x is absent, keep items unchanged.

移除列表中的值

package main
import (
  "fmt"
)
func main() {
  items := []string{"a", "b", "c", "d", "e", "f"}
  fmt.Println(items)
  x := "c"
  for i, y := range items {
    if y == x {
      items = append(items[:i], items[i+1:]...)
      break
    }
  }
  fmt.Println(items)
}
[a b c d e f]
[a b d e f]

or

for i, y := range items {
  if y == x {
    copy(items[i:], items[i+1:])
    items[len(items)-1] = nil
    items = items[:len(items)-1]
    break
  }
}
if let Some(i) = items.first(&x) {
    items.remove(i);
}

136.  Remove all occurrences of a value from a list

Remove all occurrences of value x from list items. This will alter the original list or return a new list, depending on which is more idiomatic.

从列表中删除所有出现的值

package main
import (
  "fmt"
)
func main() {
  items := []T{"b", "a", "b", "a", "r"}
  fmt.Println(items)
  var x T = "b"
  items2 := make([]T, 0, len(items))
  for _, v := range items {
    if v != x {
      items2 = append(items2, v)
    }
  }
  fmt.Println(items2)
}
type T string
[b a b a r]
[a a r]

or

package main
import (
  "fmt"
)
func main() {
  items := []T{"b", "a", "b", "a", "r"}
  fmt.Println(items)
  x := T("b")
  j := 0
  for i, v := range items {
    if v != x {
      items[j] = items[i]
      j++
    }
  }
  items = items[:j]
  fmt.Println(items)
}
type T string
[b a b a r]
[a a r]

or

package main
import (
  "fmt"
  "runtime"
)
func main() {
  var items []*image
  {
    red := newUniform(rgb{0xFF, 0, 0})
    white := newUniform(rgb{0xFF, 0xFF, 0xFF})
    items = []*image{red, white, red} // Like the flag of Austria
    fmt.Println("items =", items)
    x := red
    j := 0
    for i, v := range items {
      if v != x {
        items[j] = items[i]
        j++
      }
    }
    for k := j; k < len(items); k++ {
      items[k] = nil
    }
    items = items[:j]
  }
  // At this point, red can be garbage collected
  printAllocInfo()
  fmt.Println("items =", items) // Not the original flag anymore...
  fmt.Println("items undelying =", items[:3])
}
type image [1024][1024]rgb
type rgb [3]byte
func newUniform(color rgb) *image {
  im := new(image)
  for x := range im {
    for y := range im[x] {
      im[x][y] = color
    }
  }
  return im
}
func printAllocInfo() {
  var stats runtime.MemStats
  runtime.GC()
  runtime.ReadMemStats(&stats)
  fmt.Println("Bytes allocated (total):", stats.TotalAlloc)
  fmt.Println("Bytes still allocated:  ", stats.Alloc)
}
items = [0xc000180000 0xc000480000 0xc000180000]
Bytes allocated (total): 6416688
Bytes still allocated:   3259024
items = [0xc000480000]
items undelying = [0xc000480000 <nil> <nil>]
fn main() {
    let x = 1;
    let mut items = vec![1, 2, 3, 1, 2, 3];
    items = items.into_iter().filter(|&item| item != x).collect();
    println!("{:?}", items);
}

137. Check if string contains only digits

Set boolean b to true if string s contains only characters in range '0'..'9', false otherwise.

检查字符串是否只包含数字

package main
import (
  "fmt"
)
func main() {
  for _, s := range []string{
    "123",
    "",
    "abc123def",
    "abc",
    "123.456",
    "123 456",
  } {
    b := true
    for _, c := range s {
      if c < '0' || c > '9' {
        b = false
        break
      }
    }
    fmt.Println(s, "=>", b)
  }
}
123 => true
 => true
abc123def => false
abc => false
123.456 => false
123 456 => false

or

package main
import (
  "fmt"
  "strings"
)
func main() {
  for _, s := range []string{
    "123",
    "",
    "abc123def",
    "abc",
    "123.456",
    "123 456",
  } {
    isNotDigit := func(c rune) bool { return c < '0' || c > '9' }
    b := strings.IndexFunc(s, isNotDigit) == -1
    fmt.Println(s, "=>", b)
  }
}
123 => true
 => true
abc123def => false
abc => false
123.456 => false
123 456 => false
fn main() {
    let s = "1023";
    let chars_are_numeric: Vec<bool> = s.chars().map(|c|c.is_numeric()).collect();
    let b = !chars_are_numeric.contains(&false);
    println!("{}", b);
}

or

fn main() {
    let b = "0129".chars().all(char::is_numeric);
    println!("{}", b);
}

138. Create temp file

Create a new temporary file on filesystem.

创建一个新的临时文件

package main
import (
  "io/ioutil"
  "log"
  "os"
)
func main() {
  content := []byte("Big bag of misc data")
  log.Println("Opening new temp file")
  tmpfile, err := ioutil.TempFile("", "example")
  if err != nil {
    log.Fatal(err)
  }
  tmpfilename := tmpfile.Name()
  defer os.Remove(tmpfilename) // clean up
  log.Println("Opened new file", tmpfilename)
  log.Println("Writing [[", string(content), "]]")
  if _, err := tmpfile.Write(content); err != nil {
    log.Fatal(err)
  }
  if err := tmpfile.Close(); err != nil {
    log.Fatal(err)
  }
  log.Println("Closed", tmpfilename)
  log.Println("Opening", tmpfilename)
  buffer, err := ioutil.ReadFile(tmpfilename)
  if err != nil {
    log.Fatal(err)
  }
  log.Println("Read[[", string(buffer), "]]")
}
2009/11/10 23:00:00 Opening new temp file
2009/11/10 23:00:00 Opened new file /tmp/example067319278
2009/11/10 23:00:00 Writing [[ Big bag of misc data ]]
2009/11/10 23:00:00 Closed /tmp/example067319278
2009/11/10 23:00:00 Opening /tmp/example067319278
2009/11/10 23:00:00 Read[[ Big bag of misc data ]]
use tempdir::TempDir;
use std::fs::File;
let temp_dir = TempDir::new("prefix")?;
let temp_file = File::open(temp_dir.path().join("file_name"))?;

139. Create temp directory

Create a new temporary folder on filesystem, for writing.

创建一个临时目录

package main
import (
  "fmt"
  "io/ioutil"
  "log"
  "os"
  "path/filepath"
)
func main() {
  content := []byte("temporary file's content")
  dir, err := ioutil.TempDir("", "")
  if err != nil {
    log.Fatal(err)
  }
  defer os.RemoveAll(dir) // clean up
  inspect(dir)
  tmpfn := filepath.Join(dir, "tmpfile")
  err = ioutil.WriteFile(tmpfn, content, 0666)
  if err != nil {
    log.Fatal(err)
  }
  inspect(dir)
}
func inspect(dirpath string) {
  files, err := ioutil.ReadDir(dirpath)
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(dirpath, "contains", len(files), "files")
}
/tmp/067319278 contains 0 files
/tmp/067319278 contains 1 files
extern crate tempdir;
use tempdir::TempDir;
let tmp = TempDir::new("prefix")?;

140. Delete map entry

从map中删除某个key

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