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.


目录
相关文章
|
算法 Go
Go 语言泛型 — 泛型语法与示例
本文详解 Go 语言泛型语法与使用示例,涵盖泛型函数、类型声明、类型约束及实战应用,适合入门学习与开发实践。
|
存储 安全 Java
【Golang】(4)Go里面的指针如何?函数与方法怎么不一样?带你了解Go不同于其他高级语言的语法
结构体可以存储一组不同类型的数据,是一种符合类型。Go抛弃了类与继承,同时也抛弃了构造方法,刻意弱化了面向对象的功能,Go并非是一个传统OOP的语言,但是Go依旧有着OOP的影子,通过结构体和方法也可以模拟出一个类。
668 2
|
人工智能 IDE 程序员
Go 官方宣布不再改进错误处理语法,背后原因是什么?
Go 官方发布了一篇博客文章,正式宣布:他们不会再推进任何新的错误处理语法提案。这也意味着,未来编写 Go 代码时,你依然会频繁地写下那句熟悉的 if err != nil {return err}。
305 0
|
Rust 安全 编译器
30天拿下Rust之语法大全
Rust是一种系统级编程语言,以其独特的所有权系统和内存安全性受到开发者青睐。本文从基本数据类型入手,介绍了标量类型如整数、浮点数、布尔值及字符,复合类型如元组、数组和结构体等。此外,还探讨了变量与常量的声明与使用,条件判断与循环语句的语法,以及函数定义与调用的方法。文章通过示例代码展示了如何使用Rust编写简洁高效的程序,并简要介绍了注释与宏的概念,为读者快速掌握这门语言提供了实用指南。欲获取最新文章或交流技术问题,请关注微信公众号“希望睿智”。
594 1
|
Rust API
【Rust学习】09_方法语法
结构体让你可以创建出在你的领域中有意义的自定义类型。通过结构体,我们可以将相关联的数据片段联系起来并命名它们,这样可以使得代码更加清晰。在 impl 块中,你可以定义与你的类型相关联的函数,而方法是一种相关联的函数,允许您指定结构体的实例具有的行为。 但是结构体并不是创建自定义类型的唯一方式:让我们转向 Rust 的 enum 功能,将另一个工具添加到你的工具箱中。
317 0
|
Java 编译器 Go
Go to Learn Go之基础语法
Go to Learn Go之基础语法
285 0
|
Rust Linux Go
Rust/Go语言学习
Rust/Go语言学习
Rust 中使用 :: 这种语法的几种情况
Rust 中使用 :: 这种语法的几种情况
Rust的if let语法:更简洁的模式匹配
Rust的if let语法:更简洁的模式匹配
432 0
|
编译器 Go 开发者
Go语言语法基础入门
Go语言语法基础入门

热门文章

最新文章