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

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

161. Multiply all the elements of a list

Multiply all the elements of the list elements by a constant c

将list中的每个元素都乘以一个数

package main
import (
  "fmt"
)
func main() {
  const c = 5.5
  elements := []float64{2, 4, 9, 30}
  fmt.Println(elements)
  for i := range elements {
    elements[i] *= c
  }
  fmt.Println(elements)
}
[2 4 9 30]
[11 22 49.5 165]
fn main() {
    let elements: Vec<f32> = vec![2.0, 3.5, 4.0];
    let c = 2.0;
    let elements = elements.into_iter().map(|x| c * x).collect::<Vec<_>>();
    println!("{:?}", elements);
}

162. Execute procedures depending on options

execute bat if b is a program option and fox if f is a program option.

根据选项执行程序

package main
import (
  "flag"
  "fmt"
  "os"
)
func init() {
  // Just for testing in the Playground, let's simulate
  // the user called this program with command line
  // flags -f and -b
  os.Args = []string{"program", "-f", "-b"}
}
var b = flag.Bool("b", false, "Do bat")
var f = flag.Bool("f", false, "Do fox")
func main() {
  flag.Parse()
  if *b {
    bar()
  }
  if *f {
    fox()
  }
  fmt.Println("The end.")
}
func bar() {
  fmt.Println("BAR")
}
func fox() {
  fmt.Println("FOX")
}
BAR
FOX
The end.
if let Some(arg) = ::std::env::args().nth(1) {
    if &arg == "f" {
        fox();
    } else if &arg = "b" {
        bat();
    } else {
  eprintln!("invalid argument: {}", arg),
    }
} else {
    eprintln!("missing argument");
}

or

if let Some(arg) = ::std::env::args().nth(1) {
    match arg.as_str() {
        "f" => fox(),
        "b" => box(),
        _ => eprintln!("invalid argument: {}", arg),
    };
} else {
    eprintln!("missing argument");
}

163. Print list elements by group of 2

Print all the list elements, two by two, assuming list length is even.

两个一组打印数组元素

package main
import (
  "fmt"
)
func main() {
  list := []string{"a", "b", "c", "d", "e", "f"}
  for i := 0; i+1 < len(list); i += 2 {
    fmt.Println(list[i], list[i+1])
  }
}
a b
c d
e f
fn main() {
    let list = [1,2,3,4,5,6];
    for pair in list.chunks(2) {
        println!("({}, {})", pair[0], pair[1]);
    }
}
(1, 2)
(3, 4)
(5, 6)

164. Open URL in default browser

Open the URL s in the default browser. Set boolean b to indicate whether the operation was successful.

在默认浏览器中打开链接

import "github.com/skratchdot/open-golang/open"
b := open.Start(s) == nil

or

func openbrowser(url string) {
  var err error
  switch runtime.GOOS {
  case "linux":
    err = exec.Command("xdg-open", url).Start()
  case "windows":
    err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
  case "darwin":
    err = exec.Command("open", url).Start()
  default:
    err = fmt.Errorf("unsupported platform")
  }
  if err != nil {
    log.Fatal(err)
  }
}
use webbrowser;
webbrowser::open(s).expect("failed to open URL");

165. Last element of list

Assign to variable x the last element of list items.

列表中的最后一个元素

package main
import (
  "fmt"
)
func main() {
  items := []string{ "what", "a", "mess" }
  x := items[len(items)-1]
  fmt.Println(x)
}
fn main() {
    let items = vec![5, 6, 8, -20, 9, 42];
    let x = items[items.len()-1];
    println!("{:?}", x);
}

or

fn main() {
    let items = [5, 6, 8, -20, 9, 42];
    let x = items.last().unwrap();
    println!("{:?}", x);
}

166. Concatenate two lists

Create list ab containing all the elements of list a, followed by all elements of list b.

连接两个列表

package main
import (
  "fmt"
)
func main() {
  a := []string{"The ", "quick "}
  b := []string{"brown ", "fox "}
  ab := append(a, b...)
  fmt.Printf("%q", ab)
}

or

package main
import (
  "fmt"
)
func main() {
  type T string
  a := []T{"The ", "quick "}
  b := []T{"brown ", "fox "}
  var ab []T
  ab = append(append(ab, a...), b...)
  fmt.Printf("%q", ab)
}

or

package main
import (
  "fmt"
)
func main() {
  type T string
  a := []T{"The ", "quick "}
  b := []T{"brown ", "fox "}
  ab := make([]T, len(a)+len(b))
  copy(ab, a)
  copy(ab[len(a):], b)
  fmt.Printf("%q", ab)
}
fn main() {
    let a = vec![1, 2];
    let b = vec![3, 4];
    let ab = [a, b].concat();
    println!("{:?}", ab);
}

167. Trim prefix

Create string t consisting of string s with its prefix p removed (if s starts with p).

移除前缀

package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "café-society"
  p := "café"
  t := strings.TrimPrefix(s, p)
  fmt.Println(t)
}
fn main() {
    {
        let s = "pre_thing";
        let p = "pre_";
        let t = s.trim_start_matches(p);
        println!("{}", t);
    }
    {
        // Warning: trim_start_matches removes several leading occurrences of p, if present.
        let s = "pre_pre_thing";
        let p = "pre_";
        let t = s.trim_start_matches(p);
        println!("{}", t);
    }
}
thing
thing

or

fn main() {
    let s = "pre_pre_thing";
    let p = "pre_";
    let t = if s.starts_with(p) { &s[p.len()..] } else { s };
    println!("{}", t);
}

or

fn main() {
    {
        let s = "pre_thing";
        let p = "pre_";
        let t = s.strip_prefix(p).unwrap_or_else(|| s);
        println!("{}", t);
    }
    {
        // If prefix p is repeated in s, it is removed only once by strip_prefix
        let s = "pre_pre_thing";
        let p = "pre_";
        let t = s.strip_prefix(p).unwrap_or_else(|| s);
        println!("{}", t);
    }
}
thing
pre_thing

168. Trim suffix

Create string t consisting of string s with its suffix w removed (if s ends with w).

移除后缀

package main
import (
  "fmt"
  "strings"
)
func main() {
  s := "café-society"
  w := "society"
  t := strings.TrimSuffix(s, w)
  fmt.Println(t)
}
fn main() {
    let s = "thing_suf";
    let w = "_suf";
    let t = s.trim_end_matches(w);
    println!("{}", t);
    let s = "thing";
    let w = "_suf";
    let t = s.trim_end_matches(w); // s does not end with w, it is left intact
    println!("{}", t);
    let s = "thing_suf_suf";
    let w = "_suf";
    let t = s.trim_end_matches(w); // removes several occurrences of w
    println!("{}", t);
}
thing
thing
thing

or

fn main() {
    let s = "thing_suf";
    let w = "_suf";
    let t = s.strip_suffix(w).unwrap_or(s);
    println!("{}", t);
    let s = "thing";
    let w = "_suf";
    let t = s.strip_suffix(w).unwrap_or(s); // s does not end with w, it is left intact
    println!("{}", t);
    let s = "thing_suf_suf";
    let w = "_suf";
    let t = s.strip_suffix(w).unwrap_or(s); // only 1 occurrence of w is removed
    println!("{}", t);
}
thing
thing
thing_suf

169. String length

Assign to integer n the number of characters of string s. Make sure that multibyte characters are properly handled. n can be different from the number of bytes of s.

字符串长度

package main
import "fmt"
import "unicode/utf8"
func main() {
  s := "Hello, 世界"
  n := utf8.RuneCountInString(s)
  fmt.Println(n)
}
fn main() {
    let s = "世界";
    let n = s.chars().count();
    println!("{} characters", n);
}

170. Get map size

Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.

获取map的大小

package main
import "fmt"
func main() {
  mymap := map[string]int{"a": 1, "b": 2, "c": 3}
  n := len(mymap)
  fmt.Println(n)
}
use std::collections::HashMap;
fn main() {
    let mut mymap: HashMap<&str, i32> = [("one", 1), ("two", 2)].iter().cloned().collect();
    mymap.insert("three", 3);
    let n = mymap.len();
    println!("mymap has {:?} entries", n);
}
目录
相关文章
|
4月前
|
Rust 安全 程序员
|
10天前
|
Rust Linux Go
Rust/Go语言学习
Rust/Go语言学习
|
4月前
|
Rust 安全 Java
Rust 和 Go:如何选择最适合你的编程语言
Rust 和 Go 都是优秀的选择 首先,重要的是要说 Rust 和 Go 都是非常优秀的编程语言。它们都是现代的、强大的,被广泛采用,且提供了卓越的性能。
57 1
|
4月前
|
Rust 安全 程序员
Rust vs Go:解析两者的独特特性和适用场景
在讨论 Rust 与 Go 两种编程语言哪种更优秀时,我们将探讨它们在性能、简易性、安全性、功能、规模和并发处理等方面的比较。同时,我们看看它们有什么共同点和根本的差异。现在就来看看这个友好而公平的对比。
|
Rust Go C++
Rust vs Go:常用语法对比(十三)(1)
Rust vs Go:常用语法对比(十三)(1)
76 0
|
Rust Go C++
Rust vs Go:常用语法对比(十三)(2)
Rust vs Go:常用语法对比(十三)(2)
90 1
|
Rust Go C++
Rust vs Go:常用语法对比(十二)(2)
Rust vs Go:常用语法对比(十二)(2)
75 0
|
Rust Go C++
Rust vs Go:常用语法对比(十二)(1)
Rust vs Go:常用语法对比(十二)(1)
78 0
|
Rust Go C++
Rust vs Go:常用语法对比(十一)(2)
Rust vs Go:常用语法对比(十一)(2)
65 0
|
Rust Go C++
Rust vs Go:常用语法对比(十一)(1)
Rust vs Go:常用语法对比(十一)(1)
55 0