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

2023-09-05 15:43:25 浏览数 (1)

题目来自 Golang vs. Rust: Which Programming Language To Choose in 2023?[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的元素。每次迭代打印元素。

代码语言:javascript复制
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)
 }
}

代码语言:javascript复制
a
b
c
A
B
C

代码语言:javascript复制
fn main() {
    let item1 = vec!["1", "2", "3"];
    let item2 = vec!["a", "b", "c"];
    for i in item1.iter().chain(item2.iter()) {
        print!("{} ", i);
    }
}

1 2 3 a b c

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。

代码语言:javascript复制
package main

import "fmt"
import "strconv"

func main() {
 x := int64(999)
 s := strconv.FormatInt(x, 16)

 fmt.Println(s)
}

3e7

or

代码语言:javascript复制
package main

import (
 "fmt"
 "math/big"
)

func main() {
 x := big.NewInt(999)
 s := fmt.Sprintf("%x", x)

 fmt.Println(s)
}

3e7


代码语言:javascript复制
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.

代码语言:javascript复制
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.

交替迭代两个列表

代码语言:javascript复制
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])
  }
 }
}

代码语言:javascript复制
a
A
b
B
C

代码语言:javascript复制
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);
    }
}

代码语言:javascript复制
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.

检查文件是否存在

代码语言:javascript复制
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.

代码语言:javascript复制
foo.txt exists: true
bar.txt exists: false

代码语言:javascript复制
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);
}

代码语言:javascript复制
/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.

打印带时间的日志

代码语言:javascript复制
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

2009/11/10 23:00:00 Hello, playground


代码语言:javascript复制
fn main() {
    let msg = "Hello";
    eprintln!("[{}] {}", humantime::format_rfc3339_seconds(std::time::SystemTime::now()), msg);
}

[2021-07-17T07:14:03Z] Hello

146. Convert string to floating point number

Extract floating point value f from its string representation s

字符串转换为浮点型

代码语言:javascript复制
package main

import (
 "fmt"
 "strconv"
)

func main() {
 s := "3.1415926535"

 f, err := strconv.ParseFloat(s, 64)
 fmt.Printf("%T, %v, err=%vn", f, f, err)
}

//
// http://www.programming-idioms.org/idiom/146/convert-string-to-floating-point-number/1819/go
//

float64, 3.1415926535, err=<nil>


代码语言:javascript复制
fn main() {
    let s = "3.14159265359";
    let f = s.parse::<f32>().unwrap();
    
    println!("{}² = {}" , f, f * f);
}

3.1415927² = 9.869605

or

代码语言:javascript复制
fn main() {
    let s = "3.14159265359";
    let f: f32 = s.parse().unwrap();

    println!("{}² = {}", f, f * f);
}

3.1415927² = 9.869605

147. Remove all non-ASCII characters

Create string t from string s, keeping only ASCII characters

移除所有的非ASCII字符

代码语言:javascript复制
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)
}

dmi : : pklad : th d

or

代码语言:javascript复制
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)
}

5#645eyfu


代码语言:javascript复制
fn main() {
    println!("{}", "do


	

0 人点赞