Read an environment variable with the name “FOO” and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of “none”.
获取环境变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package main
import ( "fmt" "os" )
funcmain() { foo, ok := os.LookupEnv("FOO") if !ok { foo = "none" }
use std::env; ifletOk(tnt_root) = env::var("TNT_ROOT") { // }
206. Switch statement with strings
Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.
207. Allocate a list that is automatically deallocated
Allocate a list a containing n elements (n assumed to be too large for a stack) that is automatically deallocated when the program exits the scope it is declared in.
分配一个自动解除分配的列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package main
import ( "fmt" )
type T byte
funcmain() { n := 10_000_000 a := make([]T, n) fmt.Println(len(a)) }
Elements have type T. a is garbage-collected after the program exits its scope, unless we let it “escape” by taking its reference. The runtime decides if a lives in the stack on in the heap.
10000000
1
leta = vec![0; n];
Heap allocations are deallocated when the variable goes out of scope.
208. Formula with arrays
Given the arrays a,b,c,d of equal length and the scalar e, calculate a = e*(a+b*c+cos(d)). Store the results in a.
Declare a type t which contains a string s and an integer array n with variable size, and allocate a variable v of type t. Allocate v.s and v.n and set them to the values “Hello, world!” for s and [1,4,9,16,25], respectively. Deallocate v, automatically deallocating v.s and v.n (no memory leaks).
/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.
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.
funcmain() { 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) } }
1 2 3 4 5 6
--- --a -ab abc abcd --é
1 2 3 4 5 6 7 8 9 10 11 12 13
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; ifletSome(columns_short) = m.checked_sub(s.width()) { letpadding_width = c .width() .filter(|n| *n > 0) .expect("padding character should be visible"); // Saturate the columns_short letpadding_needed = columns_short + padding_width - 1 / padding_width; letmut 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.
funcmakeZip(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 }
// 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")
returnnil }
funcinit() { // 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
1 2 3 4 5 6
use zip::write::FileOptions; letpath = std::path::Path::new(_name); letfile = std::fs::File::create(&path).unwrap(); letmut zip = zip::ZipWriter::new(file); zip.start_file("readme.txt", FileOptions::default())?; zip.write_all(b"Hello, World!\n")?; zip.finish()?;
or
1 2 3 4 5 6 7 8 9 10 11 12
use zip::write::FileOptions; fnzip(_name: &str, _list: Vec<&str>) -> zip::result::ZipResult<()> { letpath = std::path::Path::new(_name); letfile = std::fs::File::create(&path).unwrap(); letmut zip = zip::ZipWriter::new(file); foriin _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.
// 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) } }
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.