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

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

91. Load JSON file into struct

json转结构体

package main
import "fmt"
import "io/ioutil"
import "encoding/json"
func readJSONFile() error {
  var x Person
  buffer, err := ioutil.ReadFile(filename)
  if err != nil {
    return err
  }
  err = json.Unmarshal(buffer, &x)
  if err != nil {
    return err
  }
  fmt.Println(x)
  return nil
}
func main() {
  err := readJSONFile()
  if err != nil {
    panic(err)
  }
}
type Person struct {
  FirstName string
  Age       int
}
const filename = "/tmp/data.json"
func init() {
  err := ioutil.WriteFile(filename, []byte(`
    {
      "FirstName":"Napoléon",
      "Age": 51 
    }`), 0644)
  if err != nil {
    panic(err)
  }
}

or

package main
import (
  "encoding/json"
  "fmt"
  "io/ioutil"
  "os"
)
func readJSONFile() error {
  var x Person
  r, err := os.Open(filename)
  if err != nil {
    return err
  }
  decoder := json.NewDecoder(r)
  err = decoder.Decode(&x)
  if err != nil {
    return err
  }
  fmt.Println(x)
  return nil
}
func main() {
  err := readJSONFile()
  if err != nil {
    panic(err)
  }
}
type Person struct {
  FirstName string
  Age       int
}
const filename = "/tmp/data.json"
func init() {
  err := ioutil.WriteFile(filename, []byte(`
    {
      "FirstName":"Napoléon",
      "Age": 51 
    }`), 0644)
  if err != nil {
    panic(err)
  }
}
#[macro_use] extern crate serde_derive;
extern crate serde_json;
use std::fs::File;
let x = ::serde_json::from_reader(File::open("data.json")?)?;

92. Save object into JSON file

将json对象写入文件

package main
import "fmt"
import "io/ioutil"
import "encoding/json"
func writeJSONFile() error {
  x := Person{
    FirstName: "Napoléon",
    Age:       51,
  }
  buffer, err := json.MarshalIndent(x, "", "  ")
  if err != nil {
    return err
  }
  return ioutil.WriteFile(filename, buffer, 0644)
}
func main() {
  err := writeJSONFile()
  if err != nil {
    panic(err)
  }
  fmt.Println("Done.")
}
type Person struct {
  FirstName string
  Age       int
}
const filename = "/tmp/data.json"

json.MarshalIndent is more human-readable than json.Marshal.

extern crate serde_json;
#[macro_use] extern crate serde_derive;
use std::fs::File;
::serde_json::to_writer(&File::create("data.json")?, &x)?

93. Pass a runnable procedure as parameter

Implement procedure control which receives one parameter f, and runs f.

以函数作为参数

package main
import "fmt"
func main() {
  control(greet)
}
func control(f func()) {
  fmt.Println("Before f")
  f()
  fmt.Println("After f")
}
func greet() {
  fmt.Println("Hello, developers")
}

Go supports first class functions, higher-order functions, user-defined function types, function literals, and closures.

Before f
Hello, developers
After f
fn control(f: impl Fn()) {
    f();
}
fn hello() {
    println!("Hello,");
}
fn main() {
    control(hello);
    control(|| { println!("Is there anybody in there?"); });
}
Hello,
Is there anybody in there?

94. Print type of variable

打印变量的类型

package main
import (
  "fmt"
  "os"
  "reflect"
)
func main() {
  var x interface{}
  x = "Hello"
  fmt.Println(reflect.TypeOf(x))
  x = 4
  fmt.Println(reflect.TypeOf(x))
  x = os.NewFile(0777, "foobar.txt")
  fmt.Println(reflect.TypeOf(x))
}
string
int
*os.File

or

package main
import (
  "fmt"
  "os"
)
func main() {
  var x interface{}
  x = "Hello"
  fmt.Printf("%T", x)
  fmt.Println()
  x = 4
  fmt.Printf("%T", x)
  fmt.Println()
  x = os.NewFile(0777, "foobar.txt")
  fmt.Printf("%T", x)
  fmt.Println()
}
string
int
*os.File
#![feature(core_intrinsics)]
fn type_of<T>(_: &T) -> String {
    format!("{}", std::intrinsics::type_name::<T>())
}
fn main() {
    let x: i32 = 1;
    println!("{}", type_of(&x));
}

95. Get file size

获取文件的大小

package main
import (
  "fmt"
  "io/ioutil"
  "os"
)
func main() {
  err := printSize("file.txt")
  if err != nil {
    panic(err)
  }
}
func printSize(path string) error {
  info, err := os.Stat(path)
  if err != nil {
    return err
  }
  x := info.Size()
  fmt.Println(x)
  return nil
}
func init() {
  // The file will only contains the characters "Hello", no newlines.
  buffer := []byte("Hello")
  err := ioutil.WriteFile("file.txt", buffer, 0644)
  if err != nil {
    panic(err)
  }
}
use std::fs;
fn filesize(path: &str) -> Result<u64, std::io::Error> {
    let x = fs::metadata(path)?.len();
    Ok(x)
}
fn main() {
    let path = "/etc/hosts";
    let x = filesize(path);
    println!("{}: {:?} bytes", path, x.unwrap());
}

or

use std::path::Path;
fn filesize(path: &std::path::Path) -> Result<u64, std::io::Error> {
    let x = path.metadata()?.len();
    Ok(x)
}
fn main() {
    let path = Path::new("/etc/hosts");
    let x = filesize(path);
    println!("{:?}: {:?} bytes", path, x.unwrap());
}

96. Check string prefix

Set boolean b to true if string s starts with prefix prefix, false otherwise.

检查两个字符串前缀是否一致

package main
import (
  "fmt"
  "strings"
)
func check(s, prefix string) {
  b := strings.HasPrefix(s, prefix)
  if b {
    fmt.Println(s, "starts with", prefix)
  } else {
    fmt.Println(s, "doesn't start with", prefix)
  }
}
func main() {
  check("bar", "foo")
  check("foobar", "foo")
}
bar doesn't start with foo
foobar starts with foo
fn main() {
    let s = "bananas";
    let prefix = "bana";
    let b = s.starts_with(prefix);
    println!("{:?}", b);
}

97. Check string suffix

Set boolean b to true if string s ends with string suffix, false otherwise.

检查字符串后缀

package main
import (
  "fmt"
  "strings"
)
func check(s, suffix string) {
  b := strings.HasSuffix(s, suffix)
  if b {
    fmt.Println(s, "ends with", suffix)
  } else {
    fmt.Println(s, "doesn't end with", suffix)
  }
}
func main() {
  check("foo", "bar")
  check("foobar", "bar")
}
foo doesn't end with bar
foobar ends with bar
fn main() {
    let s = "bananas";
    let suffix = "nas";
    let b = s.ends_with(suffix);
    println!("{:?}", b);
}

98. Epoch seconds to date object

Convert a timestamp ts (number of seconds in epoch-time) to a date with time d. E.g. 0 -> 1970-01-01 00:00:00

时间戳转日期

package main
import (
  "fmt"
  "time"
)
func main() {
  ts := int64(1451606400)
  d := time.Unix(ts, 0)
  fmt.Println(d)
}
extern crate chrono;
use chrono::prelude::*;
fn main() {
    let ts = 1451606400;
    let d = NaiveDateTime::from_timestamp(ts, 0);
    println!("{}", d);
}

99. Format date YYYY-MM-DD

Assign to string x the value of fields (year, month, day) of date d, in format YYYY-MM-DD.

时间格式转换

package main
import (
  "fmt"
  "time"
)
func main() {
  d := time.Now()
  x := d.Format("2006-01-02")
  fmt.Println(x)
  // The output may be "2009-11-10" because the Playground's clock is fixed in the past.
}
extern crate chrono;
use chrono::prelude::*;
fn main() {
    println!("{}", Utc::today().format("%Y-%m-%d"))
}

100. Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

根据某个字段排序

package main
import "fmt"
import "sort"
type Item struct {
  label string
  p     int
  lang  string
}
// c returns true if x is "inferior to" y (in a custom way)
func c(x, y Item) bool {
  return x.p < y.p
}
type ItemCSorter []Item
func (s ItemCSorter) Len() int           { return len(s) }
func (s ItemCSorter) Less(i, j int) bool { return c(s[i], s[j]) }
func (s ItemCSorter) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func sortItems(items []Item) {
  sorter := ItemCSorter(items)
  sort.Sort(sorter)
}
func main() {
  items := []Item{
    {"twelve", 12, "english"},
    {"six", 6, "english"},
    {"eleven", 11, "english"},
    {"zero", 0, "english"},
    {"two", 2, "english"},
  }
  fmt.Println("Unsorted: ", items)
  sortItems(items)
  fmt.Println("Sorted: ", items)
}

c has type func(Item, Item) bool.

Unsorted:  [{twelve 12 english} {six 6 english} {eleven 11 english} {zero 0 english} {two 2 english}]
Sorted:  [{zero 0 english} {two 2 english} {six 6 english} {eleven 11 english} {twelve 12 english}]

or

package main
import "fmt"
import "sort"
type Item struct {
  label string
  p     int
  lang  string
}
type ItemsSorter struct {
  items []Item
  c     func(x, y Item) bool
}
func (s ItemsSorter) Len() int           { return len(s.items) }
func (s ItemsSorter) Less(i, j int) bool { return s.c(s.items[i], s.items[j]) }
func (s ItemsSorter) Swap(i, j int)      { s.items[i], s.items[j] = s.items[j], s.items[i] }
func sortItems(items []Item, c func(x, y Item) bool) {
  sorter := ItemsSorter{
    items,
    c,
  }
  sort.Sort(sorter)
}
func main() {
  items := []Item{
    {"twelve", 12, "english"},
    {"six", 6, "english"},
    {"eleven", 11, "english"},
    {"zero", 0, "english"},
    {"two", 2, "english"},
  }
  fmt.Println("Unsorted: ", items)
  c := func(x, y Item) bool {
    return x.p < y.p
  }
  sortItems(items, c)
  fmt.Println("Sorted: ", items)
}

ItemsSorter contains c, which can be any comparator decided at runtime.

Unsorted:  [{twelve 12 english} {six 6 english} {eleven 11 english} {zero 0 english} {two 2 english}]
Sorted:  [{zero 0 english} {two 2 english} {six 6 english} {eleven 11 english} {twelve 12 english}]

or

package main
import "fmt"
import "sort"
type Item struct {
  label string
  p     int
  lang  string
}
// c returns true if x is "inferior to" y (in a custom way)
func c(x, y Item) bool {
  return x.p < y.p
}
func main() {
  items := []Item{
    {"twelve", 12, "english"},
    {"six", 6, "english"},
    {"eleven", 11, "english"},
    {"zero", 0, "english"},
    {"two", 2, "english"},
  }
  fmt.Println("Unsorted: ", items)
  sort.Slice(items, func(i, j int) bool {
    return c(items[i], items[j])
  })
  fmt.Println("Sorted: ", items)
}

Since Go 1.8, a single func parameter is sufficient to sort a slice.

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