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

简介: Rust vs Go:常用语法对比(8)(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);
}
目录
相关文章
|
6月前
|
Rust 安全 程序员
|
2月前
|
Rust Linux Go
Rust/Go语言学习
Rust/Go语言学习
|
6月前
|
Rust 安全 Java
Rust 和 Go:如何选择最适合你的编程语言
Rust 和 Go 都是优秀的选择 首先,重要的是要说 Rust 和 Go 都是非常优秀的编程语言。它们都是现代的、强大的,被广泛采用,且提供了卓越的性能。
76 1
|
6月前
|
Rust 安全 程序员
Rust vs Go:解析两者的独特特性和适用场景
在讨论 Rust 与 Go 两种编程语言哪种更优秀时,我们将探讨它们在性能、简易性、安全性、功能、规模和并发处理等方面的比较。同时,我们看看它们有什么共同点和根本的差异。现在就来看看这个友好而公平的对比。
|
Rust Go C++
Rust vs Go:常用语法对比(十三)(1)
Rust vs Go:常用语法对比(十三)(1)
83 0
|
Rust Go C++
Rust vs Go:常用语法对比(十三)(2)
Rust vs Go:常用语法对比(十三)(2)
96 1
|
Rust Go C++
Rust vs Go:常用语法对比(十二)(2)
Rust vs Go:常用语法对比(十二)(2)
84 0
|
Rust Go C++
Rust vs Go:常用语法对比(十二)(1)
Rust vs Go:常用语法对比(十二)(1)
88 0
|
Rust Go C++
Rust vs Go:常用语法对比(十一)(2)
Rust vs Go:常用语法对比(十一)(2)
72 0
|
Rust Go C++
Rust vs Go:常用语法对比(十一)(1)
Rust vs Go:常用语法对比(十一)(1)
63 0