Rust vs Go:常用语法对比(9)(2)

简介: Rust vs Go:常用语法对比(9)(2)

171. Add an element at the end of a list

Append element x to the list s.

在list尾部添加元素

package main
import "fmt"
func main() {
  s := []int{1, 1, 2, 3, 5, 8, 13}
  x := 21
  s = append(s, x)
  fmt.Println(s)
}
fn main() {
    let mut s = vec![1, 2, 3];
    let x = 99;
    s.push(x);
    println!("{:?}", s);
}

172. Insert entry in map

Insert value v for key k in map m.

向map中写入元素

package main
import "fmt"
func main() {
  m := map[string]int{"one": 1, "two": 2}
  k := "three"
  v := 3
  m[k] = v
  fmt.Println(m)
}
use std::collections::HashMap;
fn main() {
    let mut m: HashMap<&str, i32> = [("one", 1), ("two", 2)].iter().cloned().collect();
    let (k, v) = ("three", 3);
    m.insert(k, v);
    println!("{:?}", m);
}

173. Format a number with grouped thousands

Number will be formatted with a comma separator between every group of thousands.

按千位格式化数字

package main
import (
  "fmt"
  "golang.org/x/text/language"
  "golang.org/x/text/message"
)
// The Playground doesn't work with import of external packages.
// However, you may copy this source and test it on your workstation.
func main() {
  p := message.NewPrinter(language.English)
  s := p.Sprintf("%d\n", 1000)
  fmt.Println(s)
  // Output:
  // 1,000
}

or

package main
import (
  "fmt"
  "github.com/floscodes/golang-thousands"
  "strconv"
)
// The Playground takes more time when importing external packages.
// However, you may want to copy this source and test it on your workstation.
func main() {
  n := strconv.Itoa(23489)
  s := thousands.Separate(n, "en")
  fmt.Println(s)
  // Output:
  // 23,489
}
use separator::Separatable;
println!("{}", 1000.separated_string());

174. Make HTTP POST request

Make a HTTP request with method POST to URL u

发起http POST请求

package main
import (
  "fmt"
  "io"
  "io/ioutil"
  "net"
  "net/http"
)
func main() {
  contentType := "text/plain"
  var body io.Reader
  u := "http://" + localhost + "/hello"
  response, err := http.Post(u, contentType, body)
  check(err)
  buffer, err := ioutil.ReadAll(response.Body)
  check(err)
  fmt.Println("POST response:", response.StatusCode, string(buffer))
  response, err = http.Get(u)
  check(err)
  buffer, err = ioutil.ReadAll(response.Body)
  check(err)
  fmt.Println("GET  response:", response.StatusCode, string(buffer))
}
const localhost = "127.0.0.1:3000"
func init() {
  http.HandleFunc("/hello", myHandler)
  startServer()
}
func myHandler(w http.ResponseWriter, r *http.Request) {
  if r.Method != "POST" {
    w.WriteHeader(http.StatusBadRequest)
    fmt.Fprintf(w, "Refusing request verb %q", r.Method)
    return
  }
  fmt.Fprintf(w, "Hello POST :)")
}
func startServer() {
  listener, err := net.Listen("tcp", localhost)
  check(err)
  go http.Serve(listener, nil)
}
func check(err error) {
  if err != nil {
    panic(err)
  }
}
POST response: 200 Hello Alice (POST)
GET  response: 400 Refusing request verb "GET"

or

package main
import (
  "fmt"
  "io/ioutil"
  "net"
  "net/http"
  "net/url"
)
func main() {
  formValues := url.Values{
    "who": []string{"Alice"},
  }
  u := "http://" + localhost + "/hello"
  response, err := http.PostForm(u, formValues)
  check(err)
  buffer, err := ioutil.ReadAll(response.Body)
  check(err)
  fmt.Println("POST response:", response.StatusCode, string(buffer))
  response, err = http.Get(u)
  check(err)
  buffer, err = ioutil.ReadAll(response.Body)
  check(err)
  fmt.Println("GET  response:", response.StatusCode, string(buffer))
}
const localhost = "127.0.0.1:3000"
func init() {
  http.HandleFunc("/hello", myHandler)
  startServer()
}
func myHandler(w http.ResponseWriter, r *http.Request) {
  if r.Method != "POST" {
    w.WriteHeader(http.StatusBadRequest)
    fmt.Fprintf(w, "Refusing request verb %q", r.Method)
    return
  }
  fmt.Fprintf(w, "Hello %s (POST)", r.FormValue("who"))
}
func startServer() {
  listener, err := net.Listen("tcp", localhost)
  check(err)
  go http.Serve(listener, nil)
}
func check(err error) {
  if err != nil {
    panic(err)
  }
}
[dependencies]
error-chain = "0.12.4"
reqwest = { version = "0.11.2", features = ["blocking"] }
use error_chain::error_chain;
use std::io::Read;
let client = reqwest::blocking::Client::new();
let mut response = client.post(u).body("abc").send()?;

175. Bytes to hex string

From array a of n bytes, build the equivalent hex string s of 2n digits. Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit).

字节转十六进制字符串

package main
import (
  "encoding/hex"
  "fmt"
)
func main() {
  a := []byte("Hello")
  s := hex.EncodeToString(a)
  fmt.Println(s)
}
use core::fmt::Write;
fn main() -> core::fmt::Result {
    let a = vec![22, 4, 127, 193];
    let n = a.len();
    let mut s = String::with_capacity(2 * n);
    for byte in a {
        write!(s, "{:02X}", byte)?;
    }
    dbg!(s);
    Ok(())
}

176. Hex string to byte array

From hex string s of 2n digits, build the equivalent array a of n bytes. Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).

十六进制字符串转字节数组

package main
import (
  "encoding/hex"
  "fmt"
  "log"
)
func main() {
  s := "48656c6c6f"
  a, err := hex.DecodeString(s)
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(a)
  fmt.Println(string(a))
}
[72 101 108 108 111]
Hello
use hex::FromHex
let a: Vec<u8> = Vec::from_hex(s).expect("Invalid Hex String");

178. Check if point is inside rectangle

Set boolean b to true if if the point with coordinates (x,y) is inside the rectangle with coordinates (x1,y1,x2,y2) , or to false otherwise. Describe if the edges are considered to be inside the rectangle.

检查点是否在矩形内

package main
import (
  "fmt"
  "image"
)
func main() {
  x1, y1, x2, y2 := 1, 1, 50, 100
  r := image.Rect(x1, y1, x2, y2)
  x, y := 10, 10
  p := image.Pt(x, y)
  b := p.In(r)
  fmt.Println(b)
  x, y = 100, 100
  p = image.Pt(x, y)
  b = p.In(r)
  fmt.Println(b)
}
true
false
struct Rect {
    x1: i32,
    x2: i32,
    y1: i32,
    y2: i32,
}
impl Rect {
    fn contains(&self, x: i32, y: i32) -> bool {
        return self.x1 < x && x < self.x2 && self.y1 < y && y < self.y2;
    }
}

179. Get center of a rectangle

Return the center c of the rectangle with coördinates(x1,y1,x2,y2)

获取矩形的中心

import "image"
c := image.Pt((x1+x2)/2, (y1+y2)/2)
struct Rectangle {
    x1: f64,
    y1: f64,
    x2: f64,
    y2: f64,
}
impl Rectangle {
    pub fn center(&self) -> (f64, f64) {
      ((self.x1 + self.x2) / 2.0, (self.y1 + self.y2) / 2.0)
    }
}
fn main() {
    let r = Rectangle {
        x1: 5.,
        y1: 5.,
        x2: 10.,
        y2: 10.,
    };
    println!("{:?}", r.center());
}

180. List files in directory

Create list x containing the contents of directory d.

x may contain files and subfolders.

No recursive subfolder listing.

列出目录中的文件

package main
import (
  "fmt"
  "io/ioutil"
  "log"
)
func main() {
  d := "/"
  x, err := ioutil.ReadDir(d)
  if err != nil {
    log.Fatal(err)
  }
  for _, f := range x {
    fmt.Println(f.Name())
  }
}
.dockerenv
bin
dev
etc
home
lib
lib64
proc
root
sys
tmp
tmpfs
usr
var
use std::fs;
fn main() {
    let d = "/etc";
    let x = fs::read_dir(d).unwrap();
    for entry in x {
        let entry = entry.unwrap();
        println!("{:?}", entry.path());
    }
}

or

fn main() {
    let d = "/etc";
    let x = std::fs::read_dir(d)
        .unwrap()
        .collect::<Result<Vec<_>, _>>()
        .unwrap();
    for entry in x {
        println!("{:?}", entry.path());
    }
}
"/etc/issue.net"
"/etc/bindresvport.blacklist"
"/etc/rc1.d"
"/etc/hostname"
"/etc/xattr.conf"
"/etc/resolv.conf"
"/etc/pam.conf"
"/etc/mke2fs.conf"
"/etc/e2scrub.conf"
"/etc/update-motd.d"
"/etc/terminfo"
"/etc/alternatives"
"/etc/ld.so.cache"
"/etc/networks"
"/etc/profile"
"/etc/debconf.conf"
"/etc/security"
"/etc/.pwd.lock"
"/etc/gai.conf"
"/etc/dpkg"
"/etc/rc3.d"
"/etc/fstab"
"/etc/gshadow"
"/etc/sysctl.conf"
"/etc/rc2.d"
"/etc/selinux"
"/etc/ld.so.conf.d"
"/etc/os-release"
"/etc/libaudit.conf"
"/etc/login.defs"
"/etc/skel"
"/etc/shells"
"/etc/rc4.d"
"/etc/cron.d"
"/etc/default"
"/etc/lsb-release"
"/etc/apt"
"/etc/debian_version"
"/etc/machine-id"
"/etc/deluser.conf"
"/etc/group"
"/etc/legal"
"/etc/rc6.d"
"/etc/init.d"
"/etc/sysctl.d"
"/etc/pam.d"
"/etc/passwd"
"/etc/rc5.d"
"/etc/bash.bashrc"
"/etc/hosts"
"/etc/rc0.d"
"/etc/environment"
"/etc/cron.daily"
"/etc/shadow"
"/etc/ld.so.conf"
"/etc/subgid"
"/etc/opt"
"/etc/logrotate.d"
"/etc/subuid"
"/etc/profile.d"
"/etc/adduser.conf"
"/etc/issue"
"/etc/rmt"
"/etc/host.conf"
"/etc/rcS.d"
"/etc/nsswitch.conf"
"/etc/systemd"
"/etc/kernel"
"/etc/mtab"
"/etc/shadow-"
"/etc/passwd-"
"/etc/subuid-"
"/etc/gshadow-"
"/etc/subgid-"
"/etc/group-"
"/etc/ethertypes"
"/etc/logcheck"
"/etc/gss"
"/etc/bash_completion.d"
"/etc/X11"
"/etc/perl"
"/etc/ca-certificates"
"/etc/protocols"
"/etc/ca-certificates.conf"
"/etc/python2.7"
"/etc/localtime"
"/etc/xdg"
"/etc/timezone"
"/etc/mailcap.order"
"/etc/emacs"
"/etc/ssh"
"/etc/magic.mime"
"/etc/services"
"/etc/ssl"
"/etc/ldap"
"/etc/rpc"
"/etc/mime.types"
"/etc/magic"
"/etc/mailcap"
"/etc/inputrc"
目录
相关文章
|
18天前
|
安全 Java Go
Java vs. Go:并发之争
【4月更文挑战第20天】
22 1
|
20天前
|
Rust 安全 程序员
|
4月前
|
设计模式 Rust JavaScript
【一起学Rust | 设计模式】习惯语法——使用借用类型作为参数、格式化拼接字符串、构造函数
【一起学Rust | 设计模式】习惯语法——使用借用类型作为参数、格式化拼接字符串、构造函数
43 0
|
6月前
|
IDE Go 开发工具
Go开发IDE全览:GoLand vs VSCode全面解析
Go开发IDE全览:GoLand vs VSCode全面解析
219 0
|
15天前
|
算法 Java Go
Go vs Java:内存管理与垃圾回收机制对比
对比了Go和Java的内存管理与垃圾回收机制。Java依赖JVM自动管理内存,使用堆栈内存并采用多种垃圾回收算法,如标记-清除和分代收集。Go则提供更多的手动控制,内存分配与释放由分配器和垃圾回收器协同完成,使用三色标记算法并发回收。示例展示了Java中对象自动创建和销毁,而Go中开发者需注意内存泄漏。选择语言应根据项目需求和技术栈来决定。
|
4月前
|
设计模式 Rust Java
【一起学Rust | 设计模式】习惯语法——默认特质、集合智能指针、析构函数
【一起学Rust | 设计模式】习惯语法——默认特质、集合智能指针、析构函数
57 0
|
15天前
|
Java 大数据 Go
Go vs Java:在大数据处理领域的性能对比
Go与Java在大数据处理中各有特点。Go启动快,内存占用少,静态类型及并发模型(goroutine和channel)使其在并发性能上有优势。Java虽然启动慢,JVM内存占用高,但拥有丰富的生态系统和并发工具。代码示例展示了Go的goroutine和Java的线程池处理大数据的场景。在性能上,Go可能更优,但Java的跨平台性和生态广度使其仍被广泛应用。
|
20天前
|
存储 Rust 自然语言处理
Rust 基础语法和数据类型
Rust 基础语法和数据类型
35 0
|
20天前
|
Rust 安全 程序员
Rust vs Go:解析两者的独特特性和适用场景
在讨论 Rust 与 Go 两种编程语言哪种更优秀时,我们将探讨它们在性能、简易性、安全性、功能、规模和并发处理等方面的比较。同时,我们看看它们有什么共同点和根本的差异。现在就来看看这个友好而公平的对比。
|
9月前
|
Rust Go C++
Rust vs Go:常用语法对比(十三)(1)
Rust vs Go:常用语法对比(十三)(1)
64 0