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

alt

题目来自 Rust Vs Go: Which Language Is Better For Developing High-Performance Applications?[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.060.82-0.01-0.34-0.55}
 var s float64
 for _, d := range data {
  s += math.Pow(d, 2)
 }
 println(s)
}

+1.094200e+000


fn main() {
    let data: Vec<f32> = vec![2.03.54.0];

    let s = data.iter().map(|x| x.powi(2)).sum::<f32>();

    println!("{}", s);
}

32.25


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

none

or

package main

import (
 "fmt"
 "os"
)

func main() {
 foo := os.Getenv("FOO")
 if foo == "" {
  foo = "none"
 }

 fmt.Println(foo)
}

none


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

Called baz


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];

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.

对数组元素进行运算

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{1234}
 b := []float64{5.56.67.78.8}
 c := []float64{9101112}
 d := []float64{13141516}
 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: [f325] = [5., 2., 8., 9., 0.5]; // we want it to be mutable
    let b: [f325] = [7., 9., 8., 0.9650.98]; 
    let c: [f325] = [0., 0.8789456., 123456., 0.0003]; 
    let d: [f325] = [332., 0.18., 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
}

[470.29297, 866.57544, 536830750.0, 10127158.0, 123.7286]


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{1491625},
 }

 // 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.


211. Create folder

Create the folder at path on the filesystem

创建文件夹

package main

import (
 "fmt"
 "os"
)

func main() {
 path := "foo"
 _, err := os.Stat(path)
 b := !os.IsNotExist(err)
 fmt.Println(path, "exists:", b)

 err = os.Mkdir(path, os.ModeDir)
 if err != nil {
  panic(err)
 }

 info, err2 := os.Stat(path)
 b = !os.IsNotExist(err2)
 fmt.Println(path, "exists:", b)
 fmt.Println(path, "is a directory:", info.IsDir())
}

foo exists: false
foo exists: true
foo is a directory: true

or

package main

import (
 "fmt"
 "os"
)

func main() {
 path := "foo/bar"
 _, err := os.Stat(path)
 b := !os.IsNotExist(err)
 fmt.Println(path, "exists:", b)

 err = os.Mkdir(path, os.ModeDir)
 if err != nil {
  fmt.Println("Could not create", path, "with os.Mkdir")
 }

 info, err2 := os.Stat(path)
 b = !os.IsNotExist(err2)
 fmt.Println(path, "exists:", b)

 err = os.MkdirAll(path, os.ModeDir)
 if err != nil {
  fmt.Println("Could not create", path, "with os.MkdirAll")
 }

 info, err2 = os.Stat(path)
 b = !os.IsNotExist(err2)
 fmt.Println(path, "exists:", b)
 fmt.Println(path, "is a directory:", info.IsDir())
}
foo/bar exists: false
Could not create foo/bar with os.Mkdir
foo/bar exists: false
foo/bar exists: true
foo/bar is a directory: true

use std::fs;
use std::path::Path;

fn main() {
    let path = "/tmp/goofy";
    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);

    let r = fs::create_dir(path);
    match r {
        Err(e) => {
            println!("error creating {}: {}", path, e);
            std::process::exit(1);
        }
        Ok(_) => println!("created {}: OK", path),
    }

    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);
}

/tmp/goofy exists: false
created /tmp/goofy: OK
/tmp/goofy exists: true

or

use std::fs;
use std::path::Path;

fn main() {
    let path = "/tmp/friends/goofy";
    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);

    // fs::create_dir can't create parent folders
    let r = fs::create_dir(path);
    match r {
        Err(e) => println!("error creating {}: {}", path, e),
        Ok(_) => println!("created {}: OK", path),
    }

    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);

    // fs::create_dir_all does create parent folders
    let r = fs::create_dir_all(path);
    match r {
        Err(e) => println!("error creating {}: {}", path, e),
        Ok(_) => println!("created {}: OK", path),
    }

    let b: bool = Path::new(path).is_dir();
    println!("{} exists: {}", path, b);
}
/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.

检查文件夹是否存在

package main

import (
 "fmt"
 "os"
)

func main() {
 path := "foo"
 info, err := os.Stat(path)
 b := !os.IsNotExist(err) && info.IsDir()
 fmt.Println(path, "is a directory:", b)

 err = os.Mkdir(path, os.ModeDir)
 if err != nil {
  panic(err)
 }

 info, err = os.Stat(path)
 b = !os.IsNotExist(err) && info.IsDir()
 fmt.Println(path, "is a directory:", b)
}

foo is a directory: false
foo is a directory: true

use std::path::Path;

fn main() {
    let path = "/etc";
    let b: bool = Path::new(path).is_dir();
    println!("{}: {}", path, b);

    let path = "/goofy";
    let b: bool = Path::new(path).is_dir();
    println!("{}: {}", path, b);
}

/etc: true
/goofy: false

215. Pad string on the left

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.

左侧补齐字符串

package main

import (
 "fmt"
 "strings"
 "unicode/utf8"
)

func main() {
 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)
 }
}

---
--a
-ab
abc
abcd
--é

use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
if let Some(columns_short) = m.checked_sub(s.width()) {
    let padding_width = c
        .width()
        .filter(|n| *n > 0)
        .expect("padding character should be visible");
    // Saturate the columns_short
    let padding_needed = columns_short + padding_width - 1 / padding_width;
    let mut 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.

创建压缩文件

package main

import (
 "archive/zip"
 "bytes"
 "io"
 "io/ioutil"
 "log"
 "os"
)

func main() {
 list := []string{
  "readme.txt",
  "gopher.txt",
  "todo.txt",
 }
 name := "archive.zip"

 err := makeZip(list, name)
 if err != nil {
  log.Fatal(err)
 }
}

func makeZip(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
  }

  _, err = io.Copy(output, input)
  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")

 return nil
}

func init() {
 // 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


use zip::write::FileOptions;
let path = std::path::Path::new(_name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file); zip.start_file("readme.txt", FileOptions::default())?;                                                          
zip.write_all(b"Hello, World!\n")?;
zip.finish()?;

or

use zip::write::FileOptions;
fn zip(_name: &str, _list: Vec<&str>) -> zip::result::ZipResult<()>
{
    let path = std::path::Path::new(_name);
    let file = std::fs::File::create(&path).unwrap();
    let mut zip = zip::ZipWriter::new(file);
    for i in _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.

列表的交集

package main

import (
 "fmt"
)

type T int

func main() {
 a := []T{45678910}
 b := []T{13957977}

 // Convert to sets
 seta := make(map[T]boollen(a))
 for _, x := range a {
  seta[x] = true
 }
 setb := make(map[T]boollen(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)
  }
 }

 fmt.Println(c)
}

[5 7 9]


use std::collections::HashSet;

fn main() {
    let a = vec![1234];
    let b = vec![246822];

    let unique_a = a.iter().collect::<HashSet<_>>();
    let unique_b = b.iter().collect::<HashSet<_>>();
    let c = unique_a.intersection(&unique_b).collect::<Vec<_>>();

    println!("c: {:?}", c);
}

c: [2, 4]

or

use std::collections::HashSet;

fn main() {
    let a = vec![1234];
    let b = vec![246822];

    let set_a: HashSet<_> = a.into_iter().collect();
    let set_b: HashSet<_> = b.into_iter().collect();
    let c = set_a.intersection(&set_b);

    println!("c: {:?}", c);
}

c: [2, 4]


219. Replace multiple spaces with single space

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.

用单个空格替换多个空格

package main

import (
 "fmt"
 "regexp"
)

// regexp created only once, and then reused
var whitespaces = regexp.MustCompile(`\s+`)

func main() {
 s := `
 one   two
    three
 `


 t := whitespaces.ReplaceAllString(s, " ")

 fmt.Printf("t=%q", t)
}

t=" one two three "


use regex::Regex;

fn main() {
    let s = "
 one   two
    three
 "
;
    let re = Regex::new(r"\s+").unwrap();
    let t = re.replace_all(s, " ");
    println!("{}", t);
}

one two three


220. Create a tuple value

Create t consisting of 3 values having different types.
Explain if the elements of t are strongly typed or not.

创建元组值a

t := []interface{}{
 2.5,
 "hello",
 make(chan int),
}

A slice of empty interface may hold any values (not strongly typed).


fn main() {
    let mut t = (2.5"hello", -1);
    
    t.2 -= 4;
    println!("{:?}", t);
}

(2.5, "hello", -5)


参考资料

[1]

Rust Vs Go: Which Language Is Better For Developing High-Performance Applications?: https://analyticsindiamag.com/rust-vs-go-which-language-is-better-for-developing-high-performance-applications/

本文由 mdnice 多平台发布

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/45982.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

android数据的储存、文件的储存、SharedPreferences储存、SQLite的基本用法

一、文件的储存 1、将数据储存到文件中 Context类中提供了openfileOutput()方法&#xff0c;用来获取一个文件流&#xff0c;这个方法接收两个参数&#xff0c;第一个参数是文件名&#xff0c;在文件创建的时候使用的就是这个名称&#xff0c;注意这里指定的文件名不可以包含…

React AntDesign写一个导出数据的提示语 上面有跳转的路径,或者点击知道了,关闭该弹层

效果如下&#xff1a; 代码如下&#xff1a; ForwardDataCenterModal(_blank);export const ForwardDataCenterModal (target?: string) > {let contentBefore React.createElement(span, null, 数据正在处理中&#xff0c;请稍后前往);let contentAfter React.creat…

JAVA基础-集合(List与Map)

目录 引言 一&#xff0c;Collection集合 1.1,List接口 1.1.1&#xff0c;ArrayList 1.1.1.1&#xff0c;ArrayList的add&#xff08;&#xff09;添加方法 1.1.1.2&#xff0c;ArrayList的remove&#xff08;&#xff09;删除方法 1.1.1.3&#xff0c;ArrayList的contai…

网络超时导致namenode被kill的定位

交换机升级导致部分网络通信超时, 集群的namenode主从切换后,主namenode进程被杀死。 网络问题导致namenode与zk间的连接超时触发了hadoop集群的防脑裂机制而主动kill掉了超时的namenode进程。 日志分析发现zk和namenode之间的网络连接超时: 超时触发了namenode切换,并将超时…

游戏引擎UE如何革新影视行业?创意云全面支持UE云渲染

虚幻引擎UE&#xff08;Unreal Engine&#xff09;作为一款“殿堂级”的游戏引擎&#xff0c;占据了全球80%的商用游戏引擎市场&#xff0c;但如果仅仅将其当做游戏开发的工具&#xff0c;显然是低估了它的能力。比如迪士尼出品的电视剧《曼达洛人》、电影《狮子王》等等都使用…

白话机器学习笔记(三)评估已建立的模型

模型评估 在进行回归和分类时&#xff0c;为了进行预测&#xff0c;我们定义了函数 f θ ( x ) f_\theta(x) fθ​(x)&#xff0c;然后根据训练数据求出了函数的参数 θ \theta θ。 如何预测函数 f θ ( x ) f_\theta(x) fθ​(x)的精度&#xff1f;看它能否很好的拟合训练数…

【Django学习】(十五)API接口文档平台_项目流程分析_日志器_认证_授权

一、API接口文档平台 使用API接口文档不经可以很好的的维护接口数据&#xff0c;还给测试人员的接口测试工作带来了便利&#xff1b; 我们可以在全局配置文件中添加路由路径生成接口文档 1、使用docs接口文档维护接口 1.1在全局配置文件里指定用于支持coreapi的Schema # 指…

Linux の shell 流程控制

条件控制 # if then 如果else 没有语句 可以省略 if condition then#语句 fi# if then 。。。 else 。。。 fi if condition then#语句 else#语句 fi# if condition then#语句 elif condition2 then#语句 else#语句 fiif [ $a -gt $b ] thenecho "a > b&quo…

骆驼祥子思维导图

《骆驼祥子》简单介绍 《骆驼祥子》小说&#xff0c;以20世纪20年代的旧北京为背景。祥子所处的时代是北洋军阀统治的时代。今天我们就用ProcessOn 思维导图 来给大家解析这本名著。所有文章中的思维导图都可以到ProcessOn 模板社区获得。 1936年&#xff0c;老舍的一位山东大…

[vulnhub]DC2

文章目录 [vulnhub]DC2信息收集flag1flag2cewlwpscan flag3什么是rbash&#xff1f; flag4flag5git提权 总结 [vulnhub]DC2 信息收集 扫ip&#xff0c;有两种方式&#xff1a;arp、nmap nmap -sP 192.168.56.0/24 -T4arp-scan -l192.168.56.137 扫端口&#xff1a; nmap -…

Mendix 创客访谈录|综合业务展示大屏应用开发

本期创客 刘书智 西门子工业领域专家 我在西门子工厂自动化工程有限公司工作。一直从事SCADA产品的技术支持工作&#xff0c;已经过去17个年头了。赶上数字化发展的浪潮&#xff0c;不断学习各种IT技术&#xff0c;践行 IT与OT融合&#xff0c;希望借助自己的IT知识助力OT的发…

力扣1114.按序打印-----题目解析

题目描述 解析&#xff1a; class Foo {public int a 0;public Foo() {}public void first(Runnable printFirst) throws InterruptedException {// printFirst.run() outputs "first". Do not change or remove this line.printFirst.run();a;}public void second…

vue全局状态管理工具 Pinia 的使用

先了解一下关于Pinia的一些故事&#xff0c;面试把这些讲给面试官挺加分的&#xff0c;同时这是我持续学习下去的动力 1.为什么叫Pinia&#xff1f; 官网解释是西班牙语中的 pineapple&#xff0c;即“菠萝”&#xff0c;菠萝花是一组各自独立的花朵&#xff0c;它们结合在一起…

【C语言】函数----详解

&#x1f341; 博客主页:江池俊的博客 &#x1f4ab;收录专栏&#xff1a;C语言——探索高效编程的基石 &#x1f4bb; 其他专栏&#xff1a;数据结构探索 &#x1f3e9;代码仓库&#xff1a;江池俊的代码仓库 &#x1f3aa; 社区&#xff1a;C/C之家社区(欢迎大家加入与我一起…

安装VMware

D:\VMware\VMware Workstation\ 输入许可证

Sentinel 规则持久化到 Nacos

一、Sentinel规则管理模式&#x1f349; Sentinel的控制台规则管理有三种模式&#xff1a; 原始模式&#x1f95d; 原始模式&#xff1a;控制台配置的规则直接推送到Sentinel客户端&#xff0c;也就是我们的应用。然后保存在内存中&#xff0c;服务重启则丢失 pull模式&#…

一文详解Spring Bean循环依赖

一、背景 有好几次线上发布老应用时&#xff0c;遭遇代码启动报错&#xff0c;具体错误如下&#xff1a; Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name xxxManageFacadeImpl: Bean with name xxxManageFa…

实验数据origin作图使用经验总结

使用Origin绘制实验数据图表时&#xff0c;可以遵循以下经验总结&#xff1a; 选择合适的图表类型&#xff1a; 根据实验数据的性质和目的&#xff0c;选择合适的图表类型&#xff0c;例如散点图、折线图、柱状图、饼图等。确保图表类型能够清晰地展示数据趋势和关系。 规范坐…

常用API学习08(Java)

格式化 格式化指的是将数据按照指定的规则转化为指定的形式 。 那么为什么需要格式化&#xff1f;格式化有什么用&#xff1f; 以数字类为例&#xff0c;假设有一个比分牌&#xff0c;在无人得分的时候我们希望以&#xff1a;“00&#xff1a;00”的形式存在&#xff0c;那么…

3.安装kubesphere

1.本地存储动态 PVC # 在所有节点安装 iSCSI 协议客户端&#xff08;OpenEBS 需要该协议提供存储支持&#xff09; yum install iscsi-initiator-utils -y # 设置开机启动 systemctl enable --now iscsid # 启动服务 systemctl start iscsid # 查看服务状态 systemctl status …
最新文章