202. Sum of squares
Calculate the sum of squares s of data, an array of floating point values.
计算平方和
package main import ( "math" ) func main() { data := []float64{0.06, 0.82, -0.01, -0.34, -0.55} var s float64 for _, d := range data { s += math.Pow(d, 2) } println(s) }
fn main() { let data: Vec<f32> = vec![2.0, 3.5, 4.0]; let s = data.iter().map(|x| x.powi(2)).sum::<f32>(); println!("{}", s); }
205. Get an environment variable
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".
获取环境变量
package main import ( "fmt" "os" ) func main() { foo, ok := os.LookupEnv("FOO") if !ok { foo = "none" } fmt.Println(foo) }
or
package main import ( "fmt" "os" ) func main() { foo := os.Getenv("FOO") if foo == "" { foo = "none" } fmt.Println(foo) }
use std::env; fn main() { let foo; match env::var("FOO") { Ok(val) => foo = val, Err(_e) => foo = "none".to_string(), } println!("{}", foo); let user; match env::var("USER") { Ok(val) => user = val, Err(_e) => user = "none".to_string(), } println!("{}", user); }
none playground
or
use std::env; fn main() { let foo = env::var("FOO").unwrap_or("none".to_string()); println!("{}", foo); let user = env::var("USER").unwrap_or("none".to_string()); println!("{}", user); }
none playground
or
use std::env; fn main() { let foo = match env::var("FOO") { Ok(val) => val, Err(_e) => "none".to_string(), }; println!("{}", foo); let user = match env::var("USER") { Ok(val) => val, Err(_e) => "none".to_string(), }; println!("{}", user); }
none playground
or
use std::env; if let Ok(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.
switch语句
package main import ( "fmt" ) func main() { str := "baz" switch str { case "foo": foo() case "bar": bar() case "baz": baz() case "barfl": barfl() } } func foo() { fmt.Println("Called foo") } func bar() { fmt.Println("Called bar") } func baz() { fmt.Println("Called baz") } func barfl() { fmt.Println("Called barfl") }
fn main() { fn foo() {} fn bar() {} fn baz() {} fn barfl() {} let str_ = "x"; match str_ { "foo" => foo(), "bar" => bar(), "baz" => baz(), "barfl" => barfl(), _ => {} } }
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.
分配一个自动解除分配的列表
package main import ( "fmt" ) type T byte func main() { 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
let a = vec![0; n];
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.
对数组元素进行运算
package main import ( "fmt" "math" ) func applyFormula(a, b, c, d []float64, e float64) { for i, v := range a { a[i] = e * (v + b[i] + c[i] + math.Cos(d[i])) } } func main() { a := []float64{1, 2, 3, 4} b := []float64{5.5, 6.6, 7.7, 8.8} c := []float64{9, 10, 11, 12} d := []float64{13, 14, 15, 16} e := 42.0 fmt.Println("a is ", a) applyFormula(a, b, c, d, e) fmt.Println("a is now", a) }
a is [1 2 3 4] a is now [689.1127648209083 786.9429631647291 879.4931076599294 1001.3783018264178]
fn main() { let mut a: [f32; 5] = [5., 2., 8., 9., 0.5]; // we want it to be mutable let b: [f32; 5] = [7., 9., 8., 0.965, 0.98]; let c: [f32; 5] = [0., 0.8, 789456., 123456., 0.0003]; let d: [f32; 5] = [332., 0.1, 8., 9874., 0.3]; const e: f32 = 85.; for i in 0..a.len() { a[i] = e * (a[i] + b[i] * c[i] + d[i].cos()); } println!("{:?}", a); //Don't have any idea about the output }
209. Type with automatic deep deallocation
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).
自动深度解除分配的类型
package main func main() { f() } func f() { type t struct { s string n []int } v := t{ s: "Hello, world!", n: []int{1, 4, 9, 16, 25}, } // Pretend to use v (otherwise this is a compile error) _ = v // When f exits, v and all its fields are garbage-collected, recursively }
After v goes out of scope, v and all its fields will be garbage-collected, recursively
struct T { s: String, n: Vec<usize>, } fn main() { let v = T { s: "Hello, world!".into(), n: vec![1,4,9,16,25] }; }
When a variable goes out of scope, all member variables are deallocated recursively.