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

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

111. Launch other program

From current process, run program x with command-line parameters "a", "b".

运行其他程序

package main
import (
  "fmt"
  "os/exec"
)
func main() {
  err := exec.Command("x", "a", "b").Run()
  fmt.Println(err)
}
use std::process::Command;
fn main() {
    let child = Command::new("ls")
        .args(&["/etc"])
        .spawn()
        .expect("failed to execute process");
    let output = child.wait_with_output().expect("Failed to wait on child");
    let output = String::from_utf8(output.stdout).unwrap();
    println!("{}", output);
}
X11
adduser.conf
alternatives
apt
bash.bashrc
bash_completion.d
bindresvport.blacklist
ca-certificates
ca-certificates.conf
cron.d
cron.daily
debconf.conf
debian_version
default
deluser.conf
dpkg
e2scrub.conf
emacs
environment
ethertypes
fstab
gai.conf
group
group-
gshadow
gshadow-
gss
host.conf
hostname
hosts
init.d
inputrc
issue
issue.net
kernel
ld.so.cache
ld.so.conf
ld.so.conf.d
ldap
legal
libaudit.conf
localtime
logcheck
login.defs
logrotate.d
lsb-release
machine-id
magic
magic.mime
mailcap
mailcap.order
mime.types
mke2fs.conf
mtab
networks
nsswitch.conf
opt
os-release
pam.conf
pam.d
passwd
passwd-
perl
profile
profile.d
protocols
python2.7
rc0.d
rc1.d
rc2.d
rc3.d
rc4.d
rc5.d
rc6.d
rcS.d
resolv.conf
rmt
rpc
security
selinux
services
shadow
shadow-
shells
skel
ssh
ssl
subgid
subgid-
subuid
subuid-
sysctl.conf
sysctl.d
systemd
terminfo
timezone
update-motd.d
xattr.conf
xdg

or

use std::process::Command;
fn main() {
    let output = Command::new("ls")
        .args(&["/etc"])
        .output()
        .expect("failed to execute process");
    let output = String::from_utf8(output.stdout).unwrap();
    println!("{}", output);
}

or

use std::process::Command;
fn main() {
    let status = Command::new("ls")
        .args(&["/etc"])
        .status()
        .expect("failed to execute process");
    // exit code is outputted after _ls_ runs
    println!("{}", status);
}

112. Iterate over map entries, ordered by keys

Print each key k with its value x from an associative array mymap, in ascending order of k.

遍历map,按key排序

package main
import (
  "fmt"
  "sort"
)
func main() {
  mymap := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
    "four":  4,
  }
  keys := make([]string, 0, len(mymap))
  for k := range mymap {
    keys = append(keys, k)
  }
  sort.Strings(keys)
  for _, k := range keys {
    x := mymap[k]
    fmt.Println("Key =", k, ", Value =", x)
  }
}
use std::collections::BTreeMap;
fn main() {
    let mut mymap = BTreeMap::new();
    mymap.insert("one", 1);
    mymap.insert("two", 2);
    mymap.insert("three", 3);
    mymap.insert("four", 4);
    mymap.insert("five", 5);
    mymap.insert("six", 6);
    // Iterate over map entries, ordered by keys, which is NOT the numerical order
    for (k, x) in mymap {
        println!("({}, {})", k, x);
    }
}
(five, 5)
(four, 4)
(one, 1)
(six, 6)
(three, 3)
(two, 2)

113. Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x. Note that multiple entries may exist for the same value x.

遍历map,按值排序

package main
import (
  "fmt"
  "sort"
)
type entry struct {
  key   string
  value int
}
type entries []entry
func (list entries) Len() int           { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int)      { list[i], list[j] = list[j], list[i] }
func main() {
  mymap := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
    "four":  4,
    "dos":   2,
    "deux":  2,
  }
  entries := make(entries, 0, len(mymap))
  for k, x := range mymap {
    entries = append(entries, entry{key: k, value: x})
  }
  sort.Sort(entries)
  for _, e := range entries {
    fmt.Println("Key =", e.key, ", Value =", e.value)
  }
}
Key = one , Value = 1
Key = dos , Value = 2
Key = deux , Value = 2
Key = two , Value = 2
Key = three , Value = 3
Key = four , Value = 4

or

package main
import (
  "fmt"
  "sort"
)
func main() {
  mymap := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
    "four":  4,
    "dos":   2,
    "deux":  2,
  }
  type entry struct {
    key   string
    value int
  }
  entries := make([]entry, 0, len(mymap))
  for k, x := range mymap {
    entries = append(entries, entry{key: k, value: x})
  }
  sort.Slice(entries, func(i, j int) bool {
    return entries[i].value < entries[j].value
  })
  for _, e := range entries {
    fmt.Println("Key =", e.key, ", Value =", e.value)
  }
}
Key = one , Value = 1
Key = two , Value = 2
Key = dos , Value = 2
Key = deux , Value = 2
Key = three , Value = 3
Key = four , Value = 4
use itertools::Itertools;
use std::collections::HashMap;
fn main() {
    let mut mymap = HashMap::new();
    mymap.insert(1, 3);
    mymap.insert(2, 6);
    mymap.insert(3, 4);
    mymap.insert(4, 1);
    for (k, x) in mymap.iter().sorted_by_key(|x| x.1) {
        println!("[{},{}]", k, x);
    }
}
[4,1]
[1,3]
[3,4]
[2,6]

or

use std::collections::HashMap;
fn main() {
    let mut mymap = HashMap::new();
    mymap.insert(1, 3);
    mymap.insert(2, 6);
    mymap.insert(3, 4);
    mymap.insert(4, 1);
    let mut items: Vec<_> = mymap.iter().collect();
    items.sort_by_key(|item| item.1);
    for (k, x) in items {
        println!("[{},{}]", k, x);
    }
}
[4,1]
[1,3]
[3,4]
[2,6]

114. Test deep equality

Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y. Tell if the code correctly handles recursive types.

深度判等

package main
import (
  "fmt"
  "reflect"
)
func main() {
  x := Foo{9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}}
  list := []Foo{
    {9, "Bye", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
    {9, "Hello", []bool{false, false}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
    {9, "Hello", []bool{false, true}, map[int]float64{1: 3.0, 2: 2.0}, &Bar{"Babar"}},
    {9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 5: 2.0}, &Bar{"Babar"}},
    {9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Batman"}},
    {9, "Hello", []bool{false, true}, map[int]float64{1: 1.0, 2: 2.0}, &Bar{"Babar"}},
  }
  for i, y := range list {
    b := reflect.DeepEqual(x, y)
    if b {
      fmt.Println("x deep equals list[", i, "]")
    } else {
      fmt.Println("x doesn't deep equal list[", i, "]")
    }
  }
}
type Foo struct {
  int
  str     string
  bools   []bool
  mapping map[int]float64
  bar     *Bar
}
type Bar struct {
  name string
}
x doesn't deep equal list[ 0 ]
x doesn't deep equal list[ 1 ]
x doesn't deep equal list[ 2 ]
x doesn't deep equal list[ 3 ]
x doesn't deep equal list[ 4 ]
x deep equals list[ 5 ]
let b = x == y;

The == operator can only be used by having a type implement PartialEq.


115. Compare dates

Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.

日期比较

package main
import (
  "fmt"
  "time"
)
func main() {
  d1 := time.Now()
  d2 := time.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC)
  b := d1.Before(d2)
  fmt.Println(b)
}
extern crate chrono;
use chrono::prelude::*;
let b = d1 < d2;

116. Remove occurrences of word from string

Remove all occurrences of string w from string s1, and store the result in s2.

去除指定字符串

package main
import "fmt"
import "strings"
func main() {
  var s1 = "foobar"
  var w = "foo"
  s2 := strings.Replace(s1, w, "", -1)
  fmt.Println(s2)
}
fn main() {
    let s1 = "foobar";
    let w = "foo";
    let s2 = s1.replace(w, "");
    println!("{}", s2);
}

or

fn main() {
    let s1 = "foobar";
    let w = "foo";
    let s2 = str::replace(s1, w, "");
    println!("{}", s2);
}

117. Get list size

获取list的大小

package main
import "fmt"
func main() {
  // x is a slice
  x := []string{"a", "b", "c"}
  n := len(x)
  fmt.Println(n)
  // y is an array
  y := [4]string{"a", "b", "c"}
  n = len(y)
  fmt.Println(n)
}
3
4
fn main() {
    let x = vec![11, 22, 33];
    let n = x.len();
    println!("x has {} elements", n);
}

118. List to set

Create set y from list x. x may contain duplicates. y is unordered and has no repeated values.

从list到set

package main
import "fmt"
func main() {
  x := []string{"b", "a", "b", "c"}
  fmt.Println("x =", x)
  y := make(map[string]struct{}, len(x))
  for _, v := range x {
    y[v] = struct{}{}
  }
  fmt.Println("y =", y)
}
x = [b a b c]
y = map[a:{} b:{} c:{}]
use std::collections::HashSet;
fn main() {
    let x: Vec<i32> = vec![1, 7, 3, 1];
    println!("x: {:?}", x);
    let y: HashSet<_> = x.into_iter().collect();
    println!("y: {:?}", y);
}
x: [1, 7, 3, 1]
y: {1, 7, 3}

119. Deduplicate list

Remove duplicates from list x. Explain if original order is preserved.

list去重

package main
import "fmt"
func main() {
  type T string
  x := []T{"b", "a", "b", "c"}
  fmt.Println("x =", x)
  y := make(map[T]struct{}, len(x))
  for _, v := range x {
    y[v] = struct{}{}
  }
  x2 := make([]T, 0, len(y))
  for _, v := range x {
    if _, ok := y[v]; ok {
      x2 = append(x2, v)
      delete(y, v)
    }
  }
  x = x2
  fmt.Println("x =", x)
}
x = [b a b c]
x = [b a c]

or

package main
import "fmt"
func main() {
  type T string
  x := []T{"b", "a", "b", "b", "c", "b", "a"}
  fmt.Println("x =", x)
  seen := make(map[T]bool)
  j := 0
  for _, v := range x {
    if !seen[v] {
      x[j] = v
      j++
      seen[v] = true
    }
  }
  x = x[:j]
  fmt.Println("x =", x)
}
x = [b a b b c b a]
x = [b a c]

or

package main
import "fmt"
type T *int64
func main() {
  var a, b, c, d int64 = 11, 22, 33, 11
  x := []T{&b, &a, &b, &b, &c, &b, &a, &d}
  print(x)
  seen := make(map[T]bool)
  j := 0
  for _, v := range x {
    if !seen[v] {
      x[j] = v
      j++
      seen[v] = true
    }
  }
  for i := j; i < len(x); i++ {
    // Avoid memory leak
    x[i] = nil
  }
  x = x[:j]
  // Now x has only distinct pointers (even if some point to int64 values that are the same)
  print(x)
}
func print(a []T) {
  glue := ""
  for _, p := range a {
    fmt.Printf("%s%d", glue, *p)
    glue = ", "
  }
  fmt.Println()
}
22, 11, 22, 22, 33, 22, 11, 11
22, 11, 33, 11
fn main() {
    let mut x = vec![1, 2, 3, 4, 3, 2, 2, 2, 2, 2, 2];
    x.sort();
    x.dedup();
    println!("{:?}", x);
}

or

use itertools::Itertools;
fn main() {
    let x = vec![1, 2, 3, 4, 3, 2, 2, 2, 2, 2, 2];
    let dedup: Vec<_> = x.iter().unique().collect();
    println!("{:?}", dedup);
}

120. Read integer from stdin

Read an integer value from the standard input into variable n

从标准输入中读取整数

package main
import (
  "fmt"
  "io/ioutil"
  "os"
)
// This string simulates the keyboard entry.
var userInput string = `42 017`
func main() {
  var i int
  _, err := fmt.Scan(&i)
  fmt.Println(i, err)
  // The second value starts with 0, thus is interpreted as octal!
  var j int
  _, err = fmt.Scan(&j)
  fmt.Println(j, err)
}
// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
  err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
  if err != nil {
    panic(err)
  }
  fileIn, err := os.Open("/tmp/stdin")
  if err != nil {
    panic(err)
  }
  os.Stdin = fileIn
}
42 <nil>
15 <nil>

or

package main
import (
  "fmt"
  "io/ioutil"
  "os"
)
// This string simulates the keyboard entry.
var userInput string = `42 017`
func main() {
  var i int
  _, err := fmt.Scanf("%d", &i)
  fmt.Println(i, err)
  var j int
  _, err = fmt.Scanf("%d", &j)
  fmt.Println(j, err)
}
// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
  err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
  if err != nil {
    panic(err)
  }
  fileIn, err := os.Open("/tmp/stdin")
  if err != nil {
    panic(err)
  }
  os.Stdin = fileIn
}
42 <nil>
17 <nil>
fn get_input() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).expect("Failed");
    buffer
}
let n = get_input().trim().parse::<i64>().unwrap();

or

use std::io;
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();s

or

use std::io::BufRead;
let n: i32 = std::io::stdin()
    .lock()
    .lines()
    .next()
    .expect("stdin should be available")
    .expect("couldn't read from stdin")
    .trim()
    .parse()
    .expect("input was not an integer");


目录
相关文章
|
1月前
|
Rust API
【Rust学习】09_方法语法
结构体让你可以创建出在你的领域中有意义的自定义类型。通过结构体,我们可以将相关联的数据片段联系起来并命名它们,这样可以使得代码更加清晰。在 impl 块中,你可以定义与你的类型相关联的函数,而方法是一种相关联的函数,允许您指定结构体的实例具有的行为。 但是结构体并不是创建自定义类型的唯一方式:让我们转向 Rust 的 enum 功能,将另一个工具添加到你的工具箱中。
17 0
|
2月前
|
Java 编译器 Go
Go to Learn Go之基础语法
Go to Learn Go之基础语法
18 0
|
3月前
|
Rust 安全 编译器
30天拿下Rust之语法大全
Rust是一种系统级编程语言,以其独特的所有权系统和内存安全性受到开发者青睐。本文从基本数据类型入手,介绍了标量类型如整数、浮点数、布尔值及字符,复合类型如元组、数组和结构体等。此外,还探讨了变量与常量的声明与使用,条件判断与循环语句的语法,以及函数定义与调用的方法。文章通过示例代码展示了如何使用Rust编写简洁高效的程序,并简要介绍了注释与宏的概念,为读者快速掌握这门语言提供了实用指南。欲获取最新文章或交流技术问题,请关注微信公众号“希望睿智”。
49 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语言入门之路——基础语法