当前位置: 首页 > news >正文

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

alt

题图来自[1]


101. Load from HTTP GET request into a string

Make an HTTP request with method GET to URL u, then store the body of the response in string s.

发起http请求

package main

import (
 "fmt"
 "io/ioutil"
 "net"
 "net/http"
)

func main() {
 u := "http://" + localhost + "/hello?name=Inigo+Montoya"

 res, err := http.Get(u)
 check(err)
 buffer, err := ioutil.ReadAll(res.Body)
 res.Body.Close()
 check(err)
 s := string(buffer)

 fmt.Println("GET  response:", res.StatusCode, s)
}

const localhost = "127.0.0.1:3000"

func init() {
 http.HandleFunc("/hello", myHandler)
 startServer()
}

func myHandler(w http.ResponseWriter, r *http.Request) {
 fmt.Fprintf(w, "Hello %s", r.FormValue("name"))
}

func startServer() {
 listener, err := net.Listen("tcp", localhost)
 check(err)

 go http.Serve(listener, nil)
}

func check(err error) {
 if err != nil {
  panic(err)
 }
}

res has type *http.Response. buffer has type []byte. It is idiomatic and strongly recommended to check errors at each step.

GET response: 200 Hello Inigo Montoya


extern crate reqwest;
use reqwest::Client;
let client = Client::new();
let s = client.get(u).send().and_then(|res| res.text())?;

or

[dependencies]
ureq = "1.0"
let s = ureq::get(u).call().into_string()?;

or

[dependencies]
error-chain = "0.12.4"
reqwest = { version = "0.11.2", features = ["blocking"] }

use error_chain::error_chain;
use std::io::Read;
let mut response = reqwest::blocking::get(u)?;
let mut s = String::new();
response.read_to_string(&mut s)?;

102. Load from HTTP GET request into a file

Make an HTTP request with method GET to URL u, then store the body of the response in file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.

发起http请求

package main

import (
 "fmt"
 "io"
 "io/ioutil"
 "net"
 "net/http"
 "os"
)

func main() {
 err := saveGetResponse()
 check(err)
 err = readFile()
 check(err)

 fmt.Println("Done.")
}

func saveGetResponse() error {
 u := "http://" + localhost + "/hello?name=Inigo+Montoya"

 fmt.Println("Making GET request")
 resp, err := http.Get(u)
 if err != nil {
  return err
 }
 defer resp.Body.Close()
 if resp.StatusCode != 200 {
  return fmt.Errorf("Status: %v", resp.Status)
 }

 fmt.Println("Saving data to file")
 out, err := os.Create("/tmp/result.txt")
 if err != nil {
  return err
 }
 defer out.Close()
 _, err = io.Copy(out, resp.Body)
 if err != nil {
  return err
 }
 return nil
}

func readFile() error {
 fmt.Println("Reading file")
 buffer, err := ioutil.ReadFile("/tmp/result.txt")
 if err != nil {
  return err
 }
 fmt.Printf("Saved data is %q\n"string(buffer))
 return nil
}

const localhost = "127.0.0.1:3000"

func init() {
 http.HandleFunc("/hello", myHandler)
 startServer()
}

func myHandler(w http.ResponseWriter, r *http.Request) {
 fmt.Fprintf(w, "Hello %s", r.FormValue("name"))
}

func startServer() {
 listener, err := net.Listen("tcp", localhost)
 check(err)

 go http.Serve(listener, nil)
}

func check(err error) {
 if err != nil {
  panic(err)
 }
}

resp has type *http.Response. It is idiomatic and strongly recommended to check errors at each step, except for the calls to Close.

Making GET request
Saving data to file
Reading file
Saved data is "Hello Inigo Montoya"
Done.

extern crate reqwest;
use reqwest::Client;
use std::fs::File;
let client = Client::new();
match client.get(&u).send() {
    Ok(res) => {
        let file = File::create("result.txt")?;
        ::std::io::copy(res, file)?;
    },
    Err(e) => eprintln!("failed to send request: {}", e),
};

105. Current executable name

Assign to string s the name of the currently executing program (but not its full path).

当前可执行文件名称

将当前正在执行的程序的名称分配给字符串s(但不是它的完整路径)。

package main

import (
 "fmt"
 "os"
 "path/filepath"
)

func main() {
 var s string

 path := os.Args[0]
 s = filepath.Base(path)

 fmt.Println(s)
}

play


fn get_exec_name() -> Option<String> {
    std::env::current_exe()
        .ok()
        .and_then(|pb| pb.file_name().map(|s| s.to_os_string()))
        .and_then(|s| s.into_string().ok())
}

fn main() -> () {
    let s = get_exec_name().unwrap();
    println!("{}", s);
}

playground

or

fn main() {
    let s = std::env::current_exe()
        .expect("Can't get the exec path")
        .file_name()
        .expect("Can't get the exec name")
        .to_string_lossy()
        .into_owned();
    
    println!("{}", s);
}

playground


106. Get program working directory

Assign to string dir the path of the working directory. (This is not necessarily the folder containing the executable itself)

获取程序的工作路径

package main

import (
 "fmt"
 "os"
)

func main() {
 dir, err := os.Getwd()
 fmt.Println(dir, err)
}

/ <nil>


use std::env;

fn main() {
    let dir = env::current_dir().unwrap();

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

"/playground"


107. Get folder containing current program

Assign to string dir the path of the folder containing the currently running executable. (This is not necessarily the working directory, though.)

获取包含当前程序的文件夹

package main

import (
 "fmt"
 "os"
 "path/filepath"
)

func main() {
 var dir string

 programPath := os.Args[0]
 absolutePath, err := filepath.Abs(programPath)
 if err != nil {
  panic(err)
 }
 dir = filepath.Dir(absolutePath)

 fmt.Println(dir)
}

/tmpfs


let dir = std::env::current_exe()?
    .canonicalize()
    .expect("the current exe should exist")
    .parent()
    .expect("the current exe should be a file")
    .to_string_lossy()
    .to_owned();

Rust doesn't represent paths as Strings, so we need to convert the Path returned from Path::parent. This code chooses to do this lossily, replacing characters it doesn't recognize with �


109. Number of bytes of a type

Set n to the number of bytes of a variable t (of type T).

获取某个类型的字节数

package main

import (
 "fmt"
 "reflect"
)

func main() {
 var t T
 tType := reflect.TypeOf(t)
 n := tType.Size()

 fmt.Println("A", tType, "object is", n, "bytes.")
}

type Person struct {
 FirstName string
 Age       int
}

// T is a type alias, to stick to the idiom statement.
// T has the same memory footprint per value as Person.
type T Person

A main.T object is 24 bytes.


// T has (8 + 4) == 12 bytes of data
struct T(f64i32);

fn main() {
    let n = ::std::mem::size_of::<T>();

    println!("{} bytes", n);
    // T has size 16, which is "the offset in bytes between successive elements in an array with item type T"
}

16 bytes


110. Check if string is blank

Set boolean blank to true if string s is empty, or null, or contains only whitespace ; false otherwise.

检查字符串是否空白

package main

import (
 "fmt"
 "strings"
)

func main() {
 for _, s := range []string{
  "",
  "a",
  " ",
  "\t \n",
  "_",
 } {
  blank := strings.TrimSpace(s) == ""

  if blank {
   fmt.Printf("%q is blank\n", s)
  } else {
   fmt.Printf("%q is not blank\n", s)
  }
 }
}
"" is blank
"a" is not blank
" " is blank
"\t \n" is blank
"_" is not blank

fn main() {
    let list = vec![""" ""  ""\t""\n""a"" b "];
    for s in list {
        let blank = s.trim().is_empty();

        if blank {
            println!("{:?}\tis blank", s)
        } else {
            println!("{:?}\tis not blank", s)
        }
    }
}
"" is blank
" " is blank
"  " is blank
"\t" is blank
"\n" is blank
"a" is not blank
" b " is not blank

111. Launch other program

From current process, run program x with command-line parameters "a", "b".

运行其他程序

package main

import (
 "fmt"
 "os/exec"
)

func main() {
 err := exec.Command("x""a""b").Run()
 fmt.Println(err)
}

exec: "x": executable file not found in $PATH


use std::process::Command;

fn main() {
    let child = Command::new("ls")
        .args(&["/etc"])
        .spawn()
        .expect("failed to execute process");

    let output = child.wait_with_output().expect("Failed to wait on child");
    let output = String::from_utf8(output.stdout).unwrap();

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

X11
adduser.conf
alternatives
apt
bash.bashrc
bash_completion.d
bindresvport.blacklist
ca-certificates
ca-certificates.conf
cron.d
cron.daily
debconf.conf
debian_version
default
deluser.conf
dpkg
e2scrub.conf
emacs
environment
ethertypes
fstab
gai.conf
group
group-
gshadow
gshadow-
gss
host.conf
hostname
hosts
init.d
inputrc
issue
issue.net
kernel
ld.so.cache
ld.so.conf
ld.so.conf.d
ldap
legal
libaudit.conf
localtime
logcheck
login.defs
logrotate.d
lsb-release
machine-id
magic
magic.mime
mailcap
mailcap.order
mime.types
mke2fs.conf
mtab
networks
nsswitch.conf
opt
os-release
pam.conf
pam.d
passwd
passwd-
perl
profile
profile.d
protocols
python2.7
rc0.d
rc1.d
rc2.d
rc3.d
rc4.d
rc5.d
rc6.d
rcS.d
resolv.conf
rmt
rpc
security
selinux
services
shadow
shadow-
shells
skel
ssh
ssl
subgid
subgid-
subuid
subuid-
sysctl.conf
sysctl.d
systemd
terminfo
timezone
update-motd.d
xattr.conf
xdg

or

use std::process::Command;

fn main() {
    let output = Command::new("ls")
        .args(&["/etc"])
        .output()
        .expect("failed to execute process");

    let output = String::from_utf8(output.stdout).unwrap();

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

or

use std::process::Command;

fn main() {
    let status = Command::new("ls")
        .args(&["/etc"])
        .status()
        .expect("failed to execute process");

    // exit code is outputted after _ls_ runs
    println!("{}", status);
}


112. Iterate over map entries, ordered by keys

Print each key k with its value x from an associative array mymap, in ascending order of k.

遍历map,按key排序

package main

import (
 "fmt"
 "sort"
)

func main() {
 mymap := map[string]int{
  "one":   1,
  "two":   2,
  "three"3,
  "four":  4,
 }

 keys := make([]string0len(mymap))
 for k := range mymap {
  keys = append(keys, k)
 }
 sort.Strings(keys)

 for _, k := range keys {
  x := mymap[k]
  fmt.Println("Key =", k, ", Value =", x)
 }
}

Key = four , Value = 4
Key = one , Value = 1
Key = three , Value = 3
Key = two , Value = 2

use std::collections::BTreeMap;

fn main() {
    let mut mymap = BTreeMap::new();
    mymap.insert("one"1);
    mymap.insert("two"2);
    mymap.insert("three"3);
    mymap.insert("four"4);
    mymap.insert("five"5);
    mymap.insert("six"6);

    // Iterate over map entries, ordered by keys, which is NOT the numerical order
    for (k, x) in mymap {
        println!("({}, {})", k, x);
    }
}

(five, 5)
(four, 4)
(one, 1)
(six, 6)
(three, 3)
(two, 2)

113. Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x. Note that multiple entries may exist for the same value x.

遍历map,按值排序

package main

import (
 "fmt"
 "sort"
)

type entry struct {
 key   string
 value int
}
type entries []entry

func (list entries) Len() int           { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int)      { list[i], list[j] = list[j], list[i] }

func main() {
 mymap := map[string]int{
  "one":   1,
  "two":   2,
  "three"3,
  "four":  4,
  "dos":   2,
  "deux":  2,
 }

 entries := make(entries, 0len(mymap))
 for k, x := range mymap {
  entries = append(entries, entry{key: k, value: x})
 }
 sort.Sort(entries)

 for _, e := range entries {
  fmt.Println("Key =", e.key, ", Value =", e.value)
 }
}

Key = one , Value = 1
Key = dos , Value = 2
Key = deux , Value = 2
Key = two , Value = 2
Key = three , Value = 3
Key = four , Value = 4

or

package main

import (
 "fmt"
 "sort"
)

func main() {
 mymap := map[string]int{
  "one":   1,
  "two":   2,
  "three"3,
  "four":  4,
  "dos":   2,
  "deux":  2,
 }

 type entry struct {
  key   string
  value int
 }

 entries := make([]entry, 0len(mymap))
 for k, x := range mymap {
  entries = append(entries, entry{key: k, value: x})
 }
 sort.Slice(entries, func(i, j int) bool {
  return entries[i].value < entries[j].value
 })

 for _, e := range entries {
  fmt.Println("Key =", e.key, ", Value =", e.value)
 }
}

Key = one , Value = 1
Key = two , Value = 2
Key = dos , Value = 2
Key = deux , Value = 2
Key = three , Value = 3
Key = four , Value = 4

use itertools::Itertools;
use std::collections::HashMap;

fn main() {
    let mut mymap = HashMap::new();
    mymap.insert(13);
    mymap.insert(26);
    mymap.insert(34);
    mymap.insert(41);
    
    for (k, x) in mymap.iter().sorted_by_key(|x| x.1) {
        println!("[{},{}]", k, x);
    }
}
[4,1]
[1,3]
[3,4]
[2,6]

or

use std::collections::HashMap;

fn main() {
    let mut mymap = HashMap::new();
    mymap.insert(13);
    mymap.insert(26);
    mymap.insert(34);
    mymap.insert(41);
    
    let mut items: Vec<_> = mymap.iter().collect();
    items.sort_by_key(|item| item.1);
    for (k, x) in items {
        println!("[{},{}]", k, x);
    }
}
[4,1]
[1,3]
[3,4]
[2,6]

114. Test deep equality

Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y. Tell if the code correctly handles recursive types.

深度判等

package main

import (
 "fmt"
 "reflect"
)

func main() {
 x := Foo{9"Hello", []bool{falsetrue}, map[int]float64{11.022.0}, &Bar{"Babar"}}

 list := []Foo{
  {9"Bye", []bool{falsetrue}, map[int]float64{11.022.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsefalse}, map[int]float64{11.022.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{13.022.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{11.052.0}, &Bar{"Babar"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{11.022.0}, &Bar{"Batman"}},
  {9"Hello", []bool{falsetrue}, map[int]float64{11.022.0}, &Bar{"Babar"}},
 }

 for i, y := range list {
  b := reflect.DeepEqual(x, y)
  if b {
   fmt.Println("x deep equals list[", i, "]")

  } else {
   fmt.Println("x doesn't deep equal list[", i, "]")
  }
 }
}

type Foo struct {
 int
 str     string
 bools   []bool
 mapping map[int]float64
 bar     *Bar
}

type Bar struct {
 name string
}

x doesn't deep equal list[ 0 ]
x doesn'
t deep equal list[ 1 ]
x doesn't deep equal list[ 2 ]
x doesn'
t deep equal list[ 3 ]
x doesn't deep equal list[ 4 ]
x deep equals list[ 5 ]

let b = x == y;

The == operator can only be used by having a type implement PartialEq.


115. Compare dates

Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.

日期比较

package main

import (
 "fmt"
 "time"
)

func main() {
 d1 := time.Now()
 d2 := time.Date(2020, time.November, 1023000, time.UTC)

 b := d1.Before(d2)

 fmt.Println(b)
}

true


extern crate chrono;
use chrono::prelude::*;
let b = d1 < d2;

doc -- Struct chrono::Date[2]


116. Remove occurrences of word from string

Remove all occurrences of string w from string s1, and store the result in s2.

去除指定字符串

package main

import "fmt"
import "strings"

func main() {
 var s1 = "foobar"
 var w = "foo"
 s2 := strings.Replace(s1, w, ""-1)
 fmt.Println(s2)
}

bar


fn main() {
    let s1 = "foobar";
    let w = "foo";
    let s2 = s1.replace(w, "");
    println!("{}", s2);
}

bar

or

fn main() {
    let s1 = "foobar";
    let w = "foo";

    let s2 = str::replace(s1, w, "");

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

bar


117. Get list size

获取list的大小

package main

import "fmt"

func main() {
 // x is a slice
 x := []string{"a""b""c"}
 n := len(x)
 fmt.Println(n)

 // y is an array
 y := [4]string{"a""b""c"}
 n = len(y)
 fmt.Println(n)
}
3
4

fn main() {
    let x = vec![112233];

    let n = x.len();

    println!("x has {} elements", n);
}

x has 3 elements


118. List to set

Create set y from list x. x may contain duplicates. y is unordered and has no repeated values.

从list到set

package main

import "fmt"

func main() {
 x := []string{"b""a""b""c"}
 fmt.Println("x =", x)

 y := make(map[string]struct{}, len(x))
 for _, v := range x {
  y[v] = struct{}{}
 }

 fmt.Println("y =", y)
}
x = [b a b c]
y = map[a:{} b:{} c:{}]

use std::collections::HashSet;

fn main() {
    let x: Vec<i32> = vec![1731];
    println!("x: {:?}", x);

    let y: HashSet<_> = x.into_iter().collect();
    println!("y: {:?}", y);
}
x: [1731]
y: {173}

119. Deduplicate list

Remove duplicates from list x. Explain if original order is preserved.

list去重

package main

import "fmt"

func main() {
 type T string
 x := []T{"b""a""b""c"}
 fmt.Println("x =", x)

 y := make(map[T]struct{}, len(x))
 for _, v := range x {
  y[v] = struct{}{}
 }
 x2 := make([]T, 0len(y))
 for _, v := range x {
  if _, ok := y[v]; ok {
   x2 = append(x2, v)
   delete(y, v)
  }
 }
 x = x2

 fmt.Println("x =", x)
}

x = [b a b c]
x = [b a c]

or

package main

import "fmt"

func main() {
 type T string
 x := []T{"b""a""b""b""c""b""a"}
 fmt.Println("x =", x)

 seen := make(map[T]bool)
 j := 0
 for _, v := range x {
  if !seen[v] {
   x[j] = v
   j++
   seen[v] = true
  }
 }
 x = x[:j]

 fmt.Println("x =", x)
}
x = [b a b b c b a]
x = [b a c]

or

package main

import "fmt"

type T *int64

func main() {
 var a, b, c, d int64 = 11223311
 x := []T{&b, &a, &b, &b, &c, &b, &a, &d}
 print(x)

 seen := make(map[T]bool)
 j := 0
 for _, v := range x {
  if !seen[v] {
   x[j] = v
   j++
   seen[v] = true
  }
 }
 for i := j; i < len(x); i++ {
  // Avoid memory leak
  x[i] = nil
 }
 x = x[:j]

 // Now x has only distinct pointers (even if some point to int64 values that are the same)
 print(x)
}

func print(a []T) {
 glue := ""
 for _, p := range a {
  fmt.Printf("%s%d", glue, *p)
  glue = ", "
 }
 fmt.Println()
}
2211222233221111
22113311

fn main() {
    let mut x = vec![12343222222];
    x.sort();
    x.dedup();

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

[1, 2, 3, 4]

or

use itertools::Itertools;

fn main() {
    let x = vec![12343222222];
    let dedup: Vec<_> = x.iter().unique().collect();

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

[1, 2, 3, 4]


120. Read integer from stdin

Read an integer value from the standard input into variable n

从标准输入中读取整数

package main

import (
 "fmt"
 "io/ioutil"
 "os"
)

// This string simulates the keyboard entry.
var userInput string = `42 017`

func main() {
 var i int
 _, err := fmt.Scan(&i)
 fmt.Println(i, err)

 // The second value starts with 0, thus is interpreted as octal!
 var j int
 _, err = fmt.Scan(&j)
 fmt.Println(j, err)
}

// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
 err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
 if err != nil {
  panic(err)
 }
 fileIn, err := os.Open("/tmp/stdin")
 if err != nil {
  panic(err)
 }
 os.Stdin = fileIn
}

42 <nil>
15 <nil>

or

package main

import (
 "fmt"
 "io/ioutil"
 "os"
)

// This string simulates the keyboard entry.
var userInput string = `42 017`

func main() {
 var i int
 _, err := fmt.Scanf("%d", &i)
 fmt.Println(i, err)

 var j int
 _, err = fmt.Scanf("%d", &j)
 fmt.Println(j, err)
}

// The Go Playground doesn't actually read os.Stdin, so this
// workaround writes some data on virtual FS in a file, and then
// sets this file as the new Stdin.
//
// Note that the init func is run before main.
func init() {
 err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644)
 if err != nil {
  panic(err)
 }
 fileIn, err := os.Open("/tmp/stdin")
 if err != nil {
  panic(err)
 }
 os.Stdin = fileIn
}
42 <nil>
17 <nil>

fn get_input() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).expect("Failed");
    buffer
}

let n = get_input().trim().parse::<i64>().unwrap();

or

use std::io;
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();s

or

use std::io::BufRead;
let n: i32 = std::io::stdin()
    .lock()
    .lines()
    .next()
    .expect("stdin should be available")
    .expect("couldn't read from stdin")
    .trim()
    .parse()
    .expect("input was not an integer");

参考资料

[1]

题图来自: https://picx.zhimg.com/v2-363b653b2429b2f8073bc067b6c55f2d_720w.jpg?source=172ae18b

[2]

doc -- Struct chrono::Date: https://docs.rs/chrono/0.4.3/chrono/struct.Date.html

本文由 mdnice 多平台发布

相关文章:

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

题图来自[1] 101. Load from HTTP GET request into a string Make an HTTP request with method GET to URL u, then store the body of the response in string s. 发起http请求 package mainimport ( "fmt" "io/ioutil" "net" "net/http…...

css元素定位:通过元素的标签或者元素的id、class属性定位

前言 大部分人在使用selenium定位元素时&#xff0c;用的是xpath元素定位方式&#xff0c;因为xpath元素定位方式基本能解决定位的需求。xpath元素定位方式更直观&#xff0c;更好理解一些。 css元素定位方式往往被忽略掉了&#xff0c;其实css元素定位方式也有它的价值&…...

java享元模式

在Java中实现享元模式&#xff0c;可以通过创建一个享元工厂&#xff08;FlyweightFactory&#xff09;和享元对象&#xff08;Flyweight&#xff09;来完成。享元模式用于共享可复用对象&#xff0c;以节省内存和提高性能。 下面是一个简单的示例&#xff1a; 首先&#xff…...

ESP32(MicroPython) 两轮差速五自由度机械臂小车

这次的项目在软件上没多少调整&#xff0c;但本人希望分享一下硬件上的经验。 小车使用两轮差速底盘&#xff0c;驱动轮在小车中间&#xff0c;前后都要万向轮。这种形式可以实现0转弯半径&#xff0c;但受万向轮及用于加高的铜柱的规格限制&#xff0c;两个万向轮难以调到相同…...

mysql基本函数(五)

目录 一、数字函数二、字符函数三、日期时间函数3.1 获取系统日期时间的函数3.2 日期格式化函数3.3 日期偏移计算3.4 日期之间相隔的天数 四、条件函数4.1 IF语句4.2 条件语句 一、数字函数 函数功能用例ABS绝对值ABS(-100)ROUND四舍五入ROUND(4.62)FLOOR向下取值FLOOR(9.9)CE…...

liteflow 2.10 配置中心简单记录

除nacos是一个key 同时管理chain和script node外,可以理解为配置文件整体放到一个key下nacos下的文件必须是xml格式,系统只实现了xml parser其它etcd,zk,Apollo 是两个namespace/path(chain及script node各一)下多个key,每个key对应一个chain/node所有配置中心的核心代码…...

【C++】引用、内联函数等

文章目录 一、引用1.引用概念2.引用特性3.引用时的权限问题4 .使用场景5 .引用和指针的联系与区别 二、内联函数1.概念2.注意点 三、auto关键字1.概念2.auto的使用细则 四、 基于范围的for循环1.概念2.范围for的使用条件 五、 指针空值nullptr1.概念2.使用注意 一、引用 1.引用…...

RocketMQ教程-(4)-主题(Topic)

本文介绍 Apache RocketMQ 中主题&#xff08;Topic&#xff09;的定义、模型关系、内部属性、行为约束、版本兼容性及使用建议。 定义​ 主题是 Apache RocketMQ 中消息传输和存储的顶层容器&#xff0c;用于标识同一类业务逻辑的消息。 主题的作用主要如下&#xff1a; 定义…...

睡眠健康数据分析

项目背景 背景描述 本数据集涵盖了与睡眠和日常习惯有关的诸多变量。如性别、年龄、职业、睡眠时间、睡眠质量、身体活动水平、压力水平、BMI类别、血压、心率、每日步数、以及是否有睡眠障碍等细节。 数据集的主要特征&#xff1a; 综合睡眠指标&#xff1a; 探索睡眠持续时…...

Spring Boot 3.x 系列【47】启动流程 | 启动监听器

有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot版本3.1.0 源码地址:https://gitee.com/pearl-organization/study-spring-boot3 文章目录 1. 前言2. 核心类2.1 SpringApplicationRunListener2.2 ApplicationStartup2.3 ApplicationListener3. 执行流程3.1 获取监…...

【KD】知识蒸馏与迁移学习的不同

知识蒸馏与迁移学习的不同 (1)数据域不同. 知识蒸馏中的知识通常是在同一个目标数据集上进行迁移&#xff0c;而迁移学习中的知识往往是在不同目标的数据集上进行转移. (2)网络结构不同. 知识蒸馏的两个网络可以是同构或者异构的&#xff0c;而迁移学习通常是在单个网络上利用其…...

计算机内存中的缓存Cache Memories

这篇写一下计算机系统中的缓存Cache应用场景和实现方式介绍。 Memory hierarchy 在讲缓存之前&#xff0c;首先要了解计算机中的内存结构层次Memory hierarchy。也就是下图金字塔形状的结构。 从上到下&#xff0c;内存层次结构如下&#xff1a; 寄存器&#xff1a;这是计算机…...

Flask的send file和send_from_directory的区别

可以自行查看flask 文档。 send file高效&#xff1b; send from directory安全&#xff0c;且适用于静态资源交互。 都是实现相同的功能的。 send_file send_from_directory...

Java 队列

基本介绍 数组模拟队列 思路分析 代码实现 import java.util.Scanner;public class Test {public static void main(String[] args) {// 创建一个队列ArrayQueue queue new ArrayQueue(3);int select;Scanner scanner new Scanner(System.in);boolean loop true;while (lo…...

【算法基础:搜索与图论】3.6 二分图(染色法判定二分图匈牙利算法)

文章目录 二分图介绍染色法判定二分图例题&#xff1a;860. 染色法判定二分图 匈牙利匹配二分图最大匹配匈牙利匹配算法思想例题&#xff1a;861. 二分图的最大匹配 二分图介绍 https://oi-wiki.org/graph/bi-graph/ 二分图是图论中的一个概念&#xff0c;它的所有节点可以被…...

SpringMVC 怎么和 AJAX 相互调用的

通过 Jackson 框架就可以把 Java 里面的对象直接转化成 Js 可以识别的 Json 对象。 步骤如下 &#xff1a; a、加入 Jackson.jar b、在配置文件中配置 json 的映射 c、在接受 Ajax 方法里面可以直接返回 Object,List 等,但方法前面要加上ResponseBody 详细步骤&#xff1a; …...

UCDOS和WPS推动计算机领域的汉字化发展,中文编程该谁力扛大旗?

你还记得UCDOS吗&#xff1f; 从DOS时代过来的人&#xff0c;还知道UCDOS的&#xff0c;现在可能已经是中年人了&#xff01; 当时&#xff0c;鲍岳桥的UCDOS可以称得上是中国的国产操作系统。 在Windows还没来得及进入中国市场时&#xff0c;UCDOS可以说是走向了巅峰时刻&a…...

golang+layui提升界面美化度--[推荐]

一、背景 golanglayui提升界面美化度--[推荐]&#xff1b; golang后端写的页面很难看&#xff0c;如何好看点呢&#xff0c;那就是layui https://layui.dev/ 也是一个简单上手容易使用的框架&#xff0c;类似jquery&#xff0c;对于后端开发来说满足使用需求 二、使用注意点…...

42. 接雨水

题目介绍 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&#xff0c;计算按此排列的柱子&#xff0c;下雨之后能接多少雨水。 示例 1&#xff1a; 输入&#xff1a;height [0,1,0,2,1,0,1,3,2,1,2,1] 输出&#xff1a;6 解释&#xff1a;上面是由数组 [0,1,0,2,1,0,1,3…...

Python学习阶段路线和内容

Python学习阶段路线和内容 这是我的看法和认识&#xff0c;供参考。 Python学习路线主要分为三个阶段&#xff1a;入门阶段、提高阶段和深入阶段。 入门阶段 入门阶段需要学习Python的基本语法&#xff0c;掌握变量和数据类型、条件语句和循环语句、函数和模块等内容。并通过…...

深入浅出Asp.Net Core MVC应用开发系列-AspNetCore中的日志记录

ASP.NET Core 是一个跨平台的开源框架&#xff0c;用于在 Windows、macOS 或 Linux 上生成基于云的新式 Web 应用。 ASP.NET Core 中的日志记录 .NET 通过 ILogger API 支持高性能结构化日志记录&#xff0c;以帮助监视应用程序行为和诊断问题。 可以通过配置不同的记录提供程…...

51c自动驾驶~合集58

我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留&#xff0c;CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制&#xff08;CCA-Attention&#xff09;&#xff0c;…...

SciencePlots——绘制论文中的图片

文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了&#xff1a;一行…...

MySQL 隔离级别:脏读、幻读及不可重复读的原理与示例

一、MySQL 隔离级别 MySQL 提供了四种隔离级别,用于控制事务之间的并发访问以及数据的可见性,不同隔离级别对脏读、幻读、不可重复读这几种并发数据问题有着不同的处理方式,具体如下: 隔离级别脏读不可重复读幻读性能特点及锁机制读未提交(READ UNCOMMITTED)允许出现允许…...

Matlab | matlab常用命令总结

常用命令 一、 基础操作与环境二、 矩阵与数组操作(核心)三、 绘图与可视化四、 编程与控制流五、 符号计算 (Symbolic Math Toolbox)六、 文件与数据 I/O七、 常用函数类别重要提示这是一份 MATLAB 常用命令和功能的总结,涵盖了基础操作、矩阵运算、绘图、编程和文件处理等…...

前端开发面试题总结-JavaScript篇(一)

文章目录 JavaScript高频问答一、作用域与闭包1.什么是闭包&#xff08;Closure&#xff09;&#xff1f;闭包有什么应用场景和潜在问题&#xff1f;2.解释 JavaScript 的作用域链&#xff08;Scope Chain&#xff09; 二、原型与继承3.原型链是什么&#xff1f;如何实现继承&a…...

OpenLayers 分屏对比(地图联动)

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 地图分屏对比在WebGIS开发中是很常见的功能&#xff0c;和卷帘图层不一样的是&#xff0c;分屏对比是在各个地图中添加相同或者不同的图层进行对比查看。…...

2023赣州旅游投资集团

单选题 1.“不登高山&#xff0c;不知天之高也&#xff1b;不临深溪&#xff0c;不知地之厚也。”这句话说明_____。 A、人的意识具有创造性 B、人的认识是独立于实践之外的 C、实践在认识过程中具有决定作用 D、人的一切知识都是从直接经验中获得的 参考答案: C 本题解…...

JS设计模式(4):观察者模式

JS设计模式(4):观察者模式 一、引入 在开发中&#xff0c;我们经常会遇到这样的场景&#xff1a;一个对象的状态变化需要自动通知其他对象&#xff0c;比如&#xff1a; 电商平台中&#xff0c;商品库存变化时需要通知所有订阅该商品的用户&#xff1b;新闻网站中&#xff0…...

【Go语言基础【13】】函数、闭包、方法

文章目录 零、概述一、函数基础1、函数基础概念2、参数传递机制3、返回值特性3.1. 多返回值3.2. 命名返回值3.3. 错误处理 二、函数类型与高阶函数1. 函数类型定义2. 高阶函数&#xff08;函数作为参数、返回值&#xff09; 三、匿名函数与闭包1. 匿名函数&#xff08;Lambda函…...