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); }