当前位置: 首页 > 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;掌握变量和数据类型、条件语句和循环语句、函数和模块等内容。并通过…...

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …...

UE5 学习系列(三)创建和移动物体

这篇博客是该系列的第三篇&#xff0c;是在之前两篇博客的基础上展开&#xff0c;主要介绍如何在操作界面中创建和拖动物体&#xff0c;这篇博客跟随的视频链接如下&#xff1a; B 站视频&#xff1a;s03-创建和移动物体 如果你不打算开之前的博客并且对UE5 比较熟的话按照以…...

selenium学习实战【Python爬虫】

selenium学习实战【Python爬虫】 文章目录 selenium学习实战【Python爬虫】一、声明二、学习目标三、安装依赖3.1 安装selenium库3.2 安装浏览器驱动3.2.1 查看Edge版本3.2.2 驱动安装 四、代码讲解4.1 配置浏览器4.2 加载更多4.3 寻找内容4.4 完整代码 五、报告文件爬取5.1 提…...

《C++ 模板》

目录 函数模板 类模板 非类型模板参数 模板特化 函数模板特化 类模板的特化 模板&#xff0c;就像一个模具&#xff0c;里面可以将不同类型的材料做成一个形状&#xff0c;其分为函数模板和类模板。 函数模板 函数模板可以简化函数重载的代码。格式&#xff1a;templa…...

排序算法总结(C++)

目录 一、稳定性二、排序算法选择、冒泡、插入排序归并排序随机快速排序堆排序基数排序计数排序 三、总结 一、稳定性 排序算法的稳定性是指&#xff1a;同样大小的样本 **&#xff08;同样大小的数据&#xff09;**在排序之后不会改变原始的相对次序。 稳定性对基础类型对象…...

使用LangGraph和LangSmith构建多智能体人工智能系统

现在&#xff0c;通过组合几个较小的子智能体来创建一个强大的人工智能智能体正成为一种趋势。但这也带来了一些挑战&#xff0c;比如减少幻觉、管理对话流程、在测试期间留意智能体的工作方式、允许人工介入以及评估其性能。你需要进行大量的反复试验。 在这篇博客〔原作者&a…...

LRU 缓存机制详解与实现(Java版) + 力扣解决

&#x1f4cc; LRU 缓存机制详解与实现&#xff08;Java版&#xff09; 一、&#x1f4d6; 问题背景 在日常开发中&#xff0c;我们经常会使用 缓存&#xff08;Cache&#xff09; 来提升性能。但由于内存有限&#xff0c;缓存不可能无限增长&#xff0c;于是需要策略决定&am…...

华为OD机试-最短木板长度-二分法(A卷,100分)

此题是一个最大化最小值的典型例题&#xff0c; 因为搜索范围是有界的&#xff0c;上界最大木板长度补充的全部木料长度&#xff0c;下界最小木板长度&#xff1b; 即left0,right10^6; 我们可以设置一个候选值x(mid)&#xff0c;将木板的长度全部都补充到x&#xff0c;如果成功…...

在 Spring Boot 项目里,MYSQL中json类型字段使用

前言&#xff1a; 因为程序特殊需求导致&#xff0c;需要mysql数据库存储json类型数据&#xff0c;因此记录一下使用流程 1.java实体中新增字段 private List<User> users 2.增加mybatis-plus注解 TableField(typeHandler FastjsonTypeHandler.class) private Lis…...

9-Oracle 23 ai Vector Search 特性 知识准备

很多小伙伴是不是参加了 免费认证课程&#xff08;限时至2025/5/15&#xff09; Oracle AI Vector Search 1Z0-184-25考试&#xff0c;都顺利拿到certified了没。 各行各业的AI 大模型的到来&#xff0c;传统的数据库中的SQL还能不能打&#xff0c;结构化和非结构的话数据如何和…...