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

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

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.


目录
相关文章
|
11天前
|
存储 Java Go
|
3天前
|
Go
go基础语法结束篇 ——函数与方法
go基础语法结束篇 ——函数与方法
|
3天前
|
编译器 Go 数据安全/隐私保护
go语言入门之路——基础语法
go语言入门之路——基础语法
|
24天前
|
Java 编译器 Go
【字节跳动青训营】后端笔记整理-1 | Go语言入门指南:基础语法和常用特性解析(一)
本文主要梳理自第六届字节跳动青训营(后端组)-Go语言原理与实践第一节(王克纯老师主讲)。
45 1
|
26天前
|
编译器 Go
Go 语言基础语法
Go 语言基础语法
23 1
|
4天前
|
存储 安全 Java
【Go语言精进之路】Go语言基础:基础语法概览
【Go语言精进之路】Go语言基础:基础语法概览
15 0
|
11天前
|
Java Go Scala
|
11天前
|
存储 Java Unix
|
24天前
|
存储 JSON Java
【字节跳动青训营】后端笔记整理-1 | Go语言入门指南:基础语法和常用特性解析(三)
在 Go 语言里,符合语言习惯的做法是使用一个单独的返回值来传递错误信息。
31 0
|
24天前
|
存储 Go C++
【字节跳动青训营】后端笔记整理-1 | Go语言入门指南:基础语法和常用特性解析(二)
Go 语言中的复合数据类型包括数组、切片(slice)、映射(map)和结构体(struct)。
45 0