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

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

141. Iterate in sequence over two lists

Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element.

依次迭代两个列表 依次迭代列表项1和项2的元素。每次迭代打印元素。

package main
import (
  "fmt"
)
func main() {
  items1 := []string{"a", "b", "c"}
  items2 := []string{"A", "B", "C"}
  for _, v := range items1 {
    fmt.Println(v)
  }
  for _, v := range items2 {
    fmt.Println(v)
  }
}
a
b
c
A
B
C
fn main() {
    let item1 = vec!["1", "2", "3"];
    let item2 = vec!["a", "b", "c"];
    for i in item1.iter().chain(item2.iter()) {
        print!("{} ", i);
    }
}

142. Hexadecimal digits of an integer

Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> "3e7"

将整数x的十六进制表示(16进制)赋给字符串s。

package main
import "fmt"
import "strconv"
func main() {
  x := int64(999)
  s := strconv.FormatInt(x, 16)
  fmt.Println(s)
}

or

package main
import (
  "fmt"
  "math/big"
)
func main() {
  x := big.NewInt(999)
  s := fmt.Sprintf("%x", x)
  fmt.Println(s)
}
fn main() {
    let x = 999;
    let s = format!("{:X}", x);
    println!("{}", s);
    let s = format!("{:x}", x);
    println!("{}", s);
}

{:X} produces uppercase hex. {:x} produces lowercase hex.

3E7
3e7

143. Iterate alternatively over two lists

Iterate alternatively over the elements of the list items1 and items2. For each iteration, print the element.

Explain what happens if items1 and items2 have different size.

交替迭代两个列表

package main
import (
  "fmt"
)
func main() {
  items1 := []string{"a", "b"}
  items2 := []string{"A", "B", "C"}
  for i := 0; i < len(items1) || i < len(items2); i++ {
    if i < len(items1) {
      fmt.Println(items1[i])
    }
    if i < len(items2) {
      fmt.Println(items2[i])
    }
  }
}
a
A
b
B
C
extern crate itertools;
use itertools::izip;
fn main() {
    let items1 = [5, 15, 25];
    let items2 = [10, 20, 30];
    for pair in izip!(&items1, &items2) {
        println!("{}", pair.0);
        println!("{}", pair.1);
    }
}
5
10
15
20
25
30

144. Check if file exists

Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.

检查文件是否存在

package main
import (
  "fmt"
  "io/ioutil"
  "os"
)
func main() {
  fp := "foo.txt"
  _, err := os.Stat(fp)
  b := !os.IsNotExist(err)
  fmt.Println(fp, "exists:", b)
  fp = "bar.txt"
  _, err = os.Stat(fp)
  b = !os.IsNotExist(err)
  fmt.Println(fp, "exists:", b)
}
func init() {
  ioutil.WriteFile("foo.txt", []byte(`abc`), 0644)
}

There's no specific existence check func in standard library, so we have to inspect an error return value.

foo.txt exists: true
bar.txt exists: false
fn main() {
    let fp = "/etc/hosts";
    let b = std::path::Path::new(fp).exists();
    println!("{}: {}", fp, b);
    let fp = "/etc/kittens";
    let b = std::path::Path::new(fp).exists();
    println!("{}: {}", fp, b);
}
/etc/hosts: true
/etc/kittens: false

145. Print log line with datetime

Print message msg, prepended by current date and time.

Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.

打印带时间的日志

package main
import "log"
func main() {
  msg := "Hello, playground"
  log.Println(msg)
  // The date is fixed in the past in the Playground, never mind.
}
// See http://www.programming-idioms.org/idiom/145/print-log-line-with-date/1815/go
fn main() {
    let msg = "Hello";
    eprintln!("[{}] {}", humantime::format_rfc3339_seconds(std::time::SystemTime::now()), msg);
}

146. Convert string to floating point number

Extract floating point value f from its string representation s

字符串转换为浮点型

package main
import (
  "fmt"
  "strconv"
)
func main() {
  s := "3.1415926535"
  f, err := strconv.ParseFloat(s, 64)
  fmt.Printf("%T, %v, err=%v\n", f, f, err)
}
//
// http://www.programming-idioms.org/idiom/146/convert-string-to-floating-point-number/1819/go
//
fn main() {
    let s = "3.14159265359";
    let f = s.parse::<f32>().unwrap();
    println!("{}² = {}" , f, f * f);
}

or

fn main() {
    let s = "3.14159265359";
    let f: f32 = s.parse().unwrap();
    println!("{}² = {}", f, f * f);
}

147. Remove all non-ASCII characters

Create string t from string s, keeping only ASCII characters

移除所有的非ASCII字符

package main
import (
  "fmt"
  "regexp"
)
func main() {
  s := "dæmi : пример : příklad : thí dụ"
  re := regexp.MustCompile("[[:^ascii:]]")
  t := re.ReplaceAllLiteralString(s, "")
  fmt.Println(t)
}

or

package main
import (
  "fmt"
  "strings"
  "unicode"
)
func main() {
  s := "5#∑∂ƒ∞645eyfu"
  t := strings.Map(func(r rune) rune {
    if r > unicode.MaxASCII {
      return -1
    }
    return r
  }, s)
  fmt.Println(t)
}
fn main() {
    println!("{}", "do👍ot".replace(|c: char| !c.is_ascii(), ""))
}

or

fn main() {
    println!("{}", "do👍ot".replace(|c: char| !c.is_ascii(), ""))
}

148. Read list of integers from stdin

Read a list of integer numbers from the standard input, until EOF.

从stdin(标准输入)中读取整数列表

package main
import (
  "bufio"
  "fmt"
  "log"
  "strconv"
  "strings"
)
func main() {
  var ints []int
  s := bufio.NewScanner(osStdin)
  s.Split(bufio.ScanWords)
  for s.Scan() {
    i, err := strconv.Atoi(s.Text())
    if err == nil {
      ints = append(ints, i)
    }
  }
  if err := s.Err(); err != nil {
    log.Fatal(err)
  }
  fmt.Println(ints)
}
// osStdin simulates os.Stdin
var osStdin = strings.NewReader(`
11
22
33  `)
use std::{
    io::{self, Read},
    str::FromStr,
};
// dummy io::stdin
fn io_stdin() -> impl Read {
    "123
456
789"
    .as_bytes()
}
fn main() -> io::Result<()> {
    let mut string = String::new();
    io_stdin().read_to_string(&mut string)?;
    let result = string
        .lines()
        .map(i32::from_str)
        .collect::<Result<Vec<_>, _>>();
    println!("{:#?}", result);
    Ok(())
}
Ok(
    [
        123,
        456,
        789,
    ],
)

150. Remove trailing slash

Remove last character from string p, if this character is a slash /.

去除末尾的 /

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