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

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

211. Create folder

Create the folder at path on the filesystem

创建文件夹

package main
import (
  "fmt"
  "os"
)
func main() {
  path := "foo"
  _, err := os.Stat(path)
  b := !os.IsNotExist(err)
  fmt.Println(path, "exists:", b)
  err = os.Mkdir(path, os.ModeDir)
  if err != nil {
    panic(err)
  }
  info, err2 := os.Stat(path)
  b = !os.IsNotExist(err2)
  fmt.Println(path, "exists:", b)
  fmt.Println(path, "is a directory:", info.IsDir())
}
foo exists: false
foo exists: true
foo is a directory: true

or

package main
import (
  "fmt"
  "os"
)
func main() {
  path := "foo/bar"
  _, err := os.Stat(path)
  b := !os.IsNotExist(err)
  fmt.Println(path, "exists:", b)
  err = os.Mkdir(path, os.ModeDir)
  if err != nil {
    fmt.Println("Could not create", path, "with os.Mkdir")
  }
  info, err2 := os.Stat(path)
  b = !os.IsNotExist(err2)
  fmt.Println(path, "exists:", b)
  err = os.MkdirAll(path, os.ModeDir)
  if err != nil {
    fmt.Println("Could not create", path, "with os.MkdirAll")
  }
  info, err2 = os.Stat(path)
  b = !os.IsNotExist(err2)
  fmt.Println(path, "exists:", b)
  fmt.Println(path, "is a directory:", info.IsDir())
}
foo/bar exists: false
Could not create foo/bar with os.Mkdir
foo/bar exists: false
foo/bar exists: true
foo/bar is a directory: true
use std::fs;
use std::path::Path;
fn main() {
    let path = "/tmp/goofy";
    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);
    let r = fs::create_dir(path);
    match r {
        Err(e) => {
            println!("error creating {}: {}", path, e);
            std::process::exit(1);
        }
        Ok(_) => println!("created {}: OK", path),
    }
    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);
}
/tmp/goofy exists: false
created /tmp/goofy: OK
/tmp/goofy exists: true

or

use std::fs;
use std::path::Path;
fn main() {
    let path = "/tmp/friends/goofy";
    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);
    // fs::create_dir can't create parent folders
    let r = fs::create_dir(path);
    match r {
        Err(e) => println!("error creating {}: {}", path, e),
        Ok(_) => println!("created {}: OK", path),
    }
    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);
    // fs::create_dir_all does create parent folders
    let r = fs::create_dir_all(path);
    match r {
        Err(e) => println!("error creating {}: {}", path, e),
        Ok(_) => println!("created {}: OK", path),
    }
    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);
}
/tmp/friends/goofy exists: false
error creating /tmp/friends/goofy: No such file or directory (os error 2)
/tmp/friends/goofy exists: false
created /tmp/friends/goofy: OK
/tmp/friends/goofy exists: true

212. Check if folder exists

Set boolean b to true if path exists on the filesystem and is a directory; false otherwise.

检查文件夹是否存在

package main
import (
  "fmt"
  "os"
)
func main() {
  path := "foo"
  info, err := os.Stat(path)
  b := !os.IsNotExist(err) && info.IsDir()
  fmt.Println(path, "is a directory:", b)
  err = os.Mkdir(path, os.ModeDir)
  if err != nil {
    panic(err)
  }
  info, err = os.Stat(path)
  b = !os.IsNotExist(err) && info.IsDir()
  fmt.Println(path, "is a directory:", b)
}
foo is a directory: false
foo is a directory: true
use std::path::Path;
fn main() {
    let path = "/etc";
    let b: bool = Path::new(path).is_dir();
    println!("{}: {}", path, b);
    let path = "/goofy";
    let b: bool = Path::new(path).is_dir();
    println!("{}: {}", path, b);
}
/etc: true
/goofy: false

215. Pad string on the left

Prepend extra character c at the beginning of string s to make sure its length is at least m. The length is the number of characters, not the number of bytes.

左侧补齐字符串

package main
import (
  "fmt"
  "strings"
  "unicode/utf8"
)
func main() {
  m := 3
  c := "-"
  for _, s := range []string{
    "",
    "a",
    "ab",
    "abc",
    "abcd",
    "é",
  } {
    if n := utf8.RuneCountInString(s); n < m {
      s = strings.Repeat(c, m-n) + s
    }
    fmt.Println(s)
  }
}
---
--a
-ab
abc
abcd
--é
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
if let Some(columns_short) = m.checked_sub(s.width()) {
    let padding_width = c
        .width()
        .filter(|n| *n > 0)
        .expect("padding character should be visible");
    // Saturate the columns_short
    let padding_needed = columns_short + padding_width - 1 / padding_width;
    let mut t = String::with_capacity(s.len() + padding_needed);
    t.extend((0..padding_needed).map(|_| c)
    t.push_str(&s);
    s = t;
}

*This uses the Unicode display width to determine the padding needed. This will be appropriate for most uses of monospaced text.

It assumes that m won't combine with other characters to form a grapheme.*


217. Create a Zip archive

Create a zip-file with filename name and add the files listed in list to that zip-file.

创建压缩文件

package main
import (
  "archive/zip"
  "bytes"
  "io"
  "io/ioutil"
  "log"
  "os"
)
func main() {
  list := []string{
    "readme.txt",
    "gopher.txt",
    "todo.txt",
  }
  name := "archive.zip"
  err := makeZip(list, name)
  if err != nil {
    log.Fatal(err)
  }
}
func makeZip(list []string, name string) error {
  // Create a buffer to write our archive to.
  buf := new(bytes.Buffer)
  // Create a new zip archive.
  w := zip.NewWriter(buf)
  // Add some files to the archive.
  for _, filename := range list {
    // Open file for reading
    input, err := os.Open(filename)
    if err != nil {
      return err
    }
    // Create ZIP entry for writing
    output, err := w.Create(filename)
    if err != nil {
      return err
    }
    _, err = io.Copy(output, input)
    if err != nil {
      return err
    }
  }
  // Make sure to check the error on Close.
  err := w.Close()
  if err != nil {
    return err
  }
  N := buf.Len()
  err = ioutil.WriteFile(name, buf.Bytes(), 0777)
  if err != nil {
    return err
  }
  log.Println("Written a ZIP file of", N, "bytes")
  return nil
}
func init() {
  // Create some files in the filesystem.
  var files = []struct {
    Name, Body string
  }{
    {"readme.txt", "This archive contains some text files."},
    {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
    {"todo.txt", "Get animal handling licence.\nWrite more examples."},
  }
  for _, file := range files {
    err := ioutil.WriteFile(file.Name, []byte(file.Body), 0777)
    if err != nil {
      log.Fatal(err)
    }
  }
}

list contains filenames of files existing in the filesystem. In this example, the zip data is buffered in memory before writing to the filesystem.

2009/11/10 23:00:00 Written a ZIP file of 492 bytes

use zip::write::FileOptions;
let path = std::path::Path::new(_name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file); zip.start_file("readme.txt", FileOptions::default())?;                                                          
zip.write_all(b"Hello, World!\n")?;
zip.finish()?;

or

use zip::write::FileOptions;
fn zip(_name: &str, _list: Vec<&str>) -> zip::result::ZipResult<()>
{
    let path = std::path::Path::new(_name);
    let file = std::fs::File::create(&path).unwrap();
    let mut zip = zip::ZipWriter::new(file);
    for i in _list.iter() {
        zip.start_file(i as &str, FileOptions::default())?;
    }
    zip.finish()?;
    Ok(())
}

218. List intersection

Create list c containing all unique elements that are contained in both lists a and b. c should not contain any duplicates, even if a and b do. The order of c doesn't matter.

列表的交集

package main
import (
  "fmt"
)
type T int
func main() {
  a := []T{4, 5, 6, 7, 8, 9, 10}
  b := []T{1, 3, 9, 5, 7, 9, 7, 7}
  // Convert to sets
  seta := make(map[T]bool, len(a))
  for _, x := range a {
    seta[x] = true
  }
  setb := make(map[T]bool, len(a))
  for _, y := range b {
    setb[y] = true
  }
  // Iterate in one pass
  var c []T
  for x := range seta {
    if setb[x] {
      c = append(c, x)
    }
  }
  fmt.Println(c)
}
use std::collections::HashSet;
fn main() {
    let a = vec![1, 2, 3, 4];
    let b = vec![2, 4, 6, 8, 2, 2];
    let unique_a = a.iter().collect::<HashSet<_>>();
    let unique_b = b.iter().collect::<HashSet<_>>();
    let c = unique_a.intersection(&unique_b).collect::<Vec<_>>();
    println!("c: {:?}", c);
}

or

use std::collections::HashSet;
fn main() {
    let a = vec![1, 2, 3, 4];
    let b = vec![2, 4, 6, 8, 2, 2];
    let set_a: HashSet<_> = a.into_iter().collect();
    let set_b: HashSet<_> = b.into_iter().collect();
    let c = set_a.intersection(&set_b);
    println!("c: {:?}", c);
}

219. Replace multiple spaces with single space

Create string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.

用单个空格替换多个空格

package main
import (
  "fmt"
  "regexp"
)
// regexp created only once, and then reused
var whitespaces = regexp.MustCompile(`\s+`)
func main() {
  s := `
  one   two
     three
  `
  t := whitespaces.ReplaceAllString(s, " ")
  fmt.Printf("t=%q", t)
}
use regex::Regex;
fn main() {
    let s = "
  one   two
     three
  ";
    let re = Regex::new(r"\s+").unwrap();
    let t = re.replace_all(s, " ");
    println!("{}", t);
}

220. Create a tuple value

Create t consisting of 3 values having different types.

Explain if the elements of t are strongly typed or not.

创建元组值a

t := []interface{}{
  2.5,
  "hello",
  make(chan int),
}

A slice of empty interface may hold any values (not strongly typed).

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