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

简介: Rust vs Go:常用语法对比(九)(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);
}
目录
相关文章
|
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语言入门之路——基础语法