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

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

221. Remove all non-digits characters

Create string t from string s, keeping only digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

删除所有非数字字符

package main
import (
  "fmt"
  "regexp"
)
func main() {
  s := `height="168px"`
  re := regexp.MustCompile("[^\\d]")
  t := re.ReplaceAllLiteralString(s, "")
  fmt.Println(t)
}
fn main() {
    let t: String = "Today is the 14th of July"
        .chars()
        .filter(|c| c.is_digit(10))
        .collect();
    dbg!(t);
}

222. Find first index of an element in list

Set i to the first index in list items at which the element x can be found, or -1 if items does not contain x.

在列表中查找元素的第一个索引

package main
import (
  "fmt"
)
func main() {
  items := []string{"huey", "dewey", "louie"}
  x := "dewey"
  i := -1
  for j, e := range items {
    if e == x {
      i = j
      break
    }
  }
  fmt.Printf("Found %q at position %d in %q", x, i, items)
}
fn main() {
    let items = ['A', '🎂', '㍗'];
    let x = '💩';
    match items.iter().position(|y| *y == x) {
        Some(i) => println!("Found {} at position {}.", x, i),
        None => println!("There is no {} in the list.", x),
    }
}

or

fn main() {
    let items = [42, -3, 12];
    {
        let x = 12;
        let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);
        println!("{} => {}", x, i)
    }
    {
        let x = 13;
        let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);
        println!("{} => {}", x, i)
    }
}
12 => 2
13 => -1

223. for else loop

Loop through list items checking a condition. Do something else if no matches are found.

A typical use case is looping through a series of containers looking for one that matches a condition. If found, an item is inserted; otherwise, a new container is created.

These are mostly used as an inner nested loop, and in a location where refactoring inner logic into a separate function reduces clarity.

for else循环

package main
import (
  "fmt"
)
func main() {
  items := []string{"foo", "bar", "baz", "qux"}
  for _, item := range items {
    if item == "baz" {
      fmt.Println("found it")
      goto forelse
    }
  }
  {
    fmt.Println("never found it")
  }
        forelse:
}
fn main() {
    let items: &[&str] = &["foo", "bar", "baz", "qux"];
    let mut found = false;
    for item in items {
        if item == &"baz" {
            println!("found it");
            found = true;
            break;
        }
    }
    if !found {
        println!("never found it");
    }
}

or

fn main() {
     let items: &[&str] = &["foo", "bar", "baz", "qux"];
    if let None = items.iter().find(|&&item| item == "rockstar programmer") {
        println!("NotFound");
    };
}

or

fn main() {
    let items: &[&str] = &["foo", "bar", "baz", "qux"];
    items
        .iter()
        .find(|&&item| item == "rockstar programmer")
        .or_else(|| {
            println!("NotFound");
            Some(&"rockstar programmer")
        });
}

224. Add element to the beginning of the list

Insert element x at the beginning of list items.

将元素添加到列表的开头

package main
import (
  "fmt"
)
type T int
func main() {
  items := []T{42, 1337}
  var x T = 7
  items = append([]T{x}, items...)
  fmt.Println(items)
}

or

package main
import (
  "fmt"
)
type T int
func main() {
  items := []T{42, 1337}
  var x T = 7
  items = append(items, x)
  copy(items[1:], items)
  items[0] = x
  fmt.Println(items)
}
use std::collections::VecDeque;
fn main() {
    let mut items = VecDeque::new();
    items.push_back(22);
    items.push_back(33);
    let x = 11;
    items.push_front(x);
    println!("{:?}", items);
}

225. Declare and use an optional argument

Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise

声明并使用可选参数

package main
func f(x ...int) {
  if len(x) > 0 {
    println("Present", x[0])
  } else {
    println("Not present")
  }
}
func main() {
  f()
  f(1)
}

Go does not have optional arguments, but to some extend, they can be mimicked with a variadic parameter. x is a variadic parameter, which must be the last parameter for the function f. Strictly speaking, x is a list of integers, which might have more than one element. These additional elements are ignored.

Not present
Present 1
fn f(x: Option<()>) {
    match x {
        Some(x) => println!("Present {}", x),
        None => println!("Not present"),
    }
}

226. Delete last element from list

Remove the last element from list items.

从列表中删除最后一个元素

package main
import (
  "fmt"
)
func main() {
  items := []string{"banana", "apple", "kiwi"}
  fmt.Println(items)
  items = items[:len(items)-1]
  fmt.Println(items)
}
[banana apple kiwi]
[banana apple]
fn main() {
    let mut items = vec![11, 22, 33];
    items.pop();
    println!("{:?}", items);
}

227. Copy list

Create new list y containing the same elements as list x.

Subsequent modifications of y must not affect x (except for the contents referenced by the elements themselves if they contain pointers).

复制列表

package main
import (
  "fmt"
)
func main() {
  type T string
  x := []T{"Never", "gonna", "shower"}
  y := make([]T, len(x))
  copy(y, x)
  y[2] = "give"
  y = append(y, "you", "up")
  fmt.Println(x)
  fmt.Println(y)
}
[Never gonna shower]
[Never gonna give you up]
fn main() {
    let mut x = vec![4, 3, 2];
    let y = x.clone();
    x[0] = 99;
    println!("x is {:?}", x);
    println!("y is {:?}", y);
}
x is [99, 3, 2]
y is [4, 3, 2]

228. Copy a file

Copy the file at path src to dst.

复制文件

package main
import (
  "fmt"
  "io/ioutil"
  "log"
  "os"
)
func main() {
  src, dst := "/tmp/file1", "/tmp/file2"
  err := copy(dst, src)
  if err != nil {
    log.Fatalln(err)
  }
  stat, err := os.Stat(dst)
  if err != nil {
    log.Fatalln(err)
  }
  fmt.Println(dst, "exists, it has size", stat.Size(), "and mode", stat.Mode())
}
func copy(dst, src string) error {
  data, err := ioutil.ReadFile(src)
  if err != nil {
    return err
  }
  stat, err := os.Stat(src)
  if err != nil {
    return err
  }
  return ioutil.WriteFile(dst, data, stat.Mode())
}
func init() {
  data := []byte("Hello")
  err := ioutil.WriteFile("/tmp/file1", data, 0644)
  if err != nil {
    log.Fatalln(err)
  }
}

or

package main
import (
  "fmt"
  "io/ioutil"
  "log"
  "os"
)
func main() {
  src, dst := "/tmp/file1", "/tmp/file2"
  err := copy(dst, src)
  if err != nil {
    log.Fatalln(err)
  }
  stat, err := os.Stat(dst)
  if err != nil {
    log.Fatalln(err)
  }
  fmt.Println(dst, "exists, it has size", stat.Size(), "and mode", stat.Mode())
}
func copy(dst, src string) error {
  data, err := ioutil.ReadFile(src)
  if err != nil {
    return err
  }
  stat, err := os.Stat(src)
  if err != nil {
    return err
  }
  err = ioutil.WriteFile(dst, data, stat.Mode())
  if err != nil {
    return err
  }
  return os.Chmod(dst, stat.Mode())
}
func init() {
  data := []byte("Hello")
  err := ioutil.WriteFile("/tmp/file1", data, 0777)
  if err != nil {
    log.Fatalln(err)
  }
  err = os.Chmod("/tmp/file1", 0777)
  if err != nil {
    log.Fatalln(err)
  }
}

or

package main
import (
  "fmt"
  "io"
  "io/ioutil"
  "log"
  "os"
)
func main() {
  src, dst := "/tmp/file1", "/tmp/file2"
  err := copy(dst, src)
  if err != nil {
    log.Fatalln(err)
  }
  stat, err := os.Stat(dst)
  if err != nil {
    log.Fatalln(err)
  }
  fmt.Println(dst, "exists, it has size", stat.Size(), "and mode", stat.Mode())
}
func copy(dst, src string) error {
  f, err := os.Open(src)
  if err != nil {
    return err
  }
  defer f.Close()
  stat, err := f.Stat()
  if err != nil {
    return err
  }
  g, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode())
  if err != nil {
    return err
  }
  defer g.Close()
  _, err = io.Copy(g, f)
  if err != nil {
    return err
  }
  return os.Chmod(dst, stat.Mode())
}
func init() {
  data := []byte("Hello")
  err := ioutil.WriteFile("/tmp/file1", data, 0777)
  if err != nil {
    log.Fatalln(err)
  }
  err = os.Chmod("/tmp/file1", 0777)
  if err != nil {
    log.Fatalln(err)
  }
}
use std::fs;
fn main() {
    let src = "/etc/fstabZ";
    let dst = "fstab.bck";
    let r = fs::copy(src, dst);
    match r {
        Ok(v) => println!("Copied {:?} bytes", v),
        Err(e) => println!("error copying {:?} to {:?}: {:?}", src, dst, e),
    }
}
目录
相关文章
|
1月前
|
Rust 安全 编译器
30天拿下Rust之语法大全
Rust是一种系统级编程语言,以其独特的所有权系统和内存安全性受到开发者青睐。本文从基本数据类型入手,介绍了标量类型如整数、浮点数、布尔值及字符,复合类型如元组、数组和结构体等。此外,还探讨了变量与常量的声明与使用,条件判断与循环语句的语法,以及函数定义与调用的方法。文章通过示例代码展示了如何使用Rust编写简洁高效的程序,并简要介绍了注释与宏的概念,为读者快速掌握这门语言提供了实用指南。欲获取最新文章或交流技术问题,请关注微信公众号“希望睿智”。
33 1
|
22天前
|
Rust Linux Go
Rust/Go语言学习
Rust/Go语言学习
|
3月前
|
存储 Java Go
|
2月前
|
Rust
Rust 中使用 :: 这种语法的几种情况
Rust 中使用 :: 这种语法的几种情况
|
3月前
|
Rust
Rust的if let语法:更简洁的模式匹配
Rust的if let语法:更简洁的模式匹配
|
3月前
|
编译器 Go 开发者
|
3月前
|
Go
go基础语法结束篇 ——函数与方法
go基础语法结束篇 ——函数与方法
|
3月前
|
编译器 Go 数据安全/隐私保护
go语言入门之路——基础语法
go语言入门之路——基础语法
|
3月前
|
存储 安全 Java
【Go语言精进之路】Go语言基础:基础语法概览
【Go语言精进之路】Go语言基础:基础语法概览
40 0
|
3月前
|
Java Go Scala