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

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

alt

题目来自 Golang vs. Rust: Which Programming Language To Choose in 2023?[1]


141. Iterate in sequence over two lists

Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element.

依次迭代两个列表 依次迭代列表项1和项2的元素。每次迭代打印元素。

package main

import (
 "fmt"
)

func main() {
 items1 := []string{"a""b""c"}
 items2 := []string{"A""B""C"}

 for _, v := range items1 {
  fmt.Println(v)
 }
 for _, v := range items2 {
  fmt.Println(v)
 }
}

a
b
c
A
B
C

fn main() {
    let item1 = vec!["1""2""3"];
    let item2 = vec!["a""b""c"];
    for i in item1.iter().chain(item2.iter()) {
        print!("{} ", i);
    }
}

1 2 3 a b c


142. Hexadecimal digits of an integer

Assign to string s the hexadecimal representation (base 16) of integer x.
E.g. 999 -> "3e7"

将整数x的十六进制表示(16进制)赋给字符串s。

package main

import "fmt"
import "strconv"

func main() {
 x := int64(999)
 s := strconv.FormatInt(x, 16)

 fmt.Println(s)
}

3e7

or

package main

import (
 "fmt"
 "math/big"
)

func main() {
 x := big.NewInt(999)
 s := fmt.Sprintf("%x", x)

 fmt.Println(s)
}

3e7


fn main() {
    let x = 999;

    let s = format!("{:X}", x);
    println!("{}", s);

    let s = format!("{:x}", x);
    println!("{}", s);
}

{:X} produces uppercase hex. {:x} produces lowercase hex.

3E7
3e7

143. Iterate alternatively over two lists

Iterate alternatively over the elements of the list items1 and items2. For each iteration, print the element.
Explain what happens if items1 and items2 have different size.

交替迭代两个列表

package main

import (
 "fmt"
)

func main() {
 items1 := []string{"a""b"}
 items2 := []string{"A""B""C"}

 for i := 0; i < len(items1) || i < len(items2); i++ {
  if i < len(items1) {
   fmt.Println(items1[i])
  }
  if i < len(items2) {
   fmt.Println(items2[i])
  }
 }
}

a
A
b
B
C

extern crate itertools;
use itertools::izip;

fn main() {
    let items1 = [51525];
    let items2 = [102030];

    for pair in izip!(&items1, &items2) {
        println!("{}", pair.0);
        println!("{}", pair.1);
    }
}

5
10
15
20
25
30

144. Check if file exists

Set boolean b to true if file at path fp exists on filesystem; false otherwise.
Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.

检查文件是否存在

package main

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

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

 fp = "bar.txt"
 _, err = os.Stat(fp)
 b = !os.IsNotExist(err)
 fmt.Println(fp, "exists:", b)
}

func init() {
 ioutil.WriteFile("foo.txt", []byte(`abc`), 0644)
}

There's no specific existence check func in standard library, so we have to inspect an error return value.

foo.txt exists: true
bar.txt exists: false

fn main() {
    let fp = "/etc/hosts";
    let b = std::path::Path::new(fp).exists();
    println!("{}: {}", fp, b);

    let fp = "/etc/kittens";
    let b = std::path::Path::new(fp).exists();
    println!("{}: {}", fp, b);
}

/etc/hosts: true
/etc/kittens: false

145. Print log line with datetime

Print message msg, prepended by current date and time.
Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.

打印带时间的日志

package main

import "log"

func main() {
 msg := "Hello, playground"
 log.Println(msg)

 // The date is fixed in the past in the Playground, never mind.
}

// See http://www.programming-idioms.org/idiom/145/print-log-line-with-date/1815/go

2009/11/10 23:00:00 Hello, playground


fn main() {
    let msg = "Hello";
    eprintln!("[{}] {}", humantime::format_rfc3339_seconds(std::time::SystemTime::now()), msg);
}

[2021-07-17T07:14:03Z] Hello


146. Convert string to floating point number

Extract floating point value f from its string representation s

字符串转换为浮点型

package main

import (
 "fmt"
 "strconv"
)

func main() {
 s := "3.1415926535"

 f, err := strconv.ParseFloat(s, 64)
 fmt.Printf("%T, %v, err=%v\n", f, f, err)
}

//
// http://www.programming-idioms.org/idiom/146/convert-string-to-floating-point-number/1819/go
//

float64, 3.1415926535, err=<nil>


fn main() {
    let s = "3.14159265359";
    let f = s.parse::<f32>().unwrap();
    
    println!("{}² = {}" , f, f * f);
}

3.1415927² = 9.869605

or

fn main() {
    let s = "3.14159265359";
    let f: f32 = s.parse().unwrap();

    println!("{}² = {}", f, f * f);
}

3.1415927² = 9.869605


147. Remove all non-ASCII characters

Create string t from string s, keeping only ASCII characters

移除所有的非ASCII字符

package main

import (
 "fmt"
 "regexp"
)

func main() {
 s := "dæmi : пример : příklad : thí dụ"

 re := regexp.MustCompile("[[:^ascii:]]")
 t := re.ReplaceAllLiteralString(s, "")

 fmt.Println(t)
}

dmi : : pklad : th d

or

package main

import (
 "fmt"
 "strings"
 "unicode"
)

func main() {
 s := "5#∑∂ƒ∞645eyfu"
 t := strings.Map(func(r rune) rune {
  if r > unicode.MaxASCII {
   return -1
  }
  return r
 }, s)
 fmt.Println(t)
}

5#645eyfu


fn main() {
    println!("{}""do👍ot".replace(|c: char| !c.is_ascii(), ""))
}

doot

or

fn main() {
    println!("{}""do👍ot".replace(|c: char| !c.is_ascii(), ""))
}

doot


148. Read list of integers from stdin

Read a list of integer numbers from the standard input, until EOF.

从stdin(标准输入)中读取整数列表

package main

import (
 "bufio"
 "fmt"
 "log"
 "strconv"
 "strings"
)

func main() {
 var ints []int
 s := bufio.NewScanner(osStdin)
 s.Split(bufio.ScanWords)
 for s.Scan() {
  i, err := strconv.Atoi(s.Text())
  if err == nil {
   ints = append(ints, i)
  }
 }
 if err := s.Err(); err != nil {
  log.Fatal(err)
 }
 fmt.Println(ints)
}

// osStdin simulates os.Stdin
var osStdin = strings.NewReader(`
11
22
33  `
)

[11 22 33]


use std::{
    io::{self, Read},
    str::FromStr,
};

// dummy io::stdin
fn io_stdin() -> impl Read {
    "123
456
789"

    .as_bytes()
}

fn main() -> io::Result<()> {
    let mut string = String::new();
    io_stdin().read_to_string(&mut string)?;
    let result = string
        .lines()
        .map(i32::from_str)
        .collect::<Result<Vec<_>, _>>();
    println!("{:#?}", result);
    Ok(())
}
Ok(
    [
        123,
        456,
        789,
    ],
)

150. Remove trailing slash

Remove last character from string p, if this character is a slash /.

去除末尾的 /

package main

import (
 "fmt"
 "strings"
)

func main() {
 p := "/usr/bin/"

 p = strings.TrimSuffix(p, "/")

 fmt.Println(p)
}

/usr/bin


fn main() {
    let mut p = String::from("Dddd/");
    if p.ends_with('/') {
        p.pop();
    }
    println!("{}", p);
}

Dddd


151. Remove string trailing path separator

Remove last character from string p, if this character is the file path separator of current platform.
Note that this also transforms unix root path "/" into the empty string!

删除字符串尾部路径分隔符

package main

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

func main() {
 p := somePath()
 fmt.Println(p)

 sep := fmt.Sprintf("%c", os.PathSeparator)
 p = strings.TrimSuffix(p, sep)

 fmt.Println(p)
}

func somePath() string {
 dir, err := ioutil.TempDir("""")
 if err != nil {
  panic(err)
 }
 p := fmt.Sprintf("%s%c%s%c", dir, os.PathSeparator, "foobar", os.PathSeparator)
 return p
}

/tmp/067319278/foobar/
/tmp/067319278/foobar

or

package main

import (
 "fmt"
 "io/ioutil"
 "os"
 "path/filepath"
 "strings"
)

func main() {
 p := somePath()
 fmt.Println(p)

 sep := fmt.Sprintf("%c", filepath.Separator)
 p = strings.TrimSuffix(p, sep)

 fmt.Println(p)
}

func somePath() string {
 dir, err := ioutil.TempDir("""")
 if err != nil {
  panic(err)
 }
 p := fmt.Sprintf("%s%c%s%c", dir, os.PathSeparator, "foobar", os.PathSeparator)
 return p
}
/tmp/065654753/foobar/
/tmp/065654753/foobar

fn main() {
    {
        let p = "/tmp/";

        let p = if ::std::path::is_separator(p.chars().last().unwrap()) {
            &p[0..p.len() - 1]
        } else {
            p
        };

        println!("{}", p);
    }
    
    {
        let p = "/tmp";

        let p = if ::std::path::is_separator(p.chars().last().unwrap()) {
            &p[0..p.len() - 1]
        } else {
            p
        };

        println!("{}", p);
    }
}
/tmp
/tmp

or

fn main() {
    {
        let mut p = "/tmp/";

        p = p.strip_suffix(std::path::is_separator).unwrap_or(p);

        println!("{}", p);
    }
    
    {
        let mut p = "/tmp";

        p = p.strip_suffix(std::path::is_separator).unwrap_or(p);

        println!("{}", p);
    }
}
/tmp
/tmp

152. Turn a character into a string

Create string s containing only the character c.

将字符转换成字符串

package main

import (
 "fmt"
 "os"
)

func main() {
 var c rune = os.PathSeparator
 fmt.Printf("%c \n", c)

 s := fmt.Sprintf("%c", c)
 fmt.Printf("%#v \n", s)
}


"/" 

fn main() {
    let c = 'a';
    
    let s = c.to_string();
    
    println!("{}", s);
}

a


153. Concatenate string with integer

Create string t as the concatenation of string s and integer i.

连接字符串和整数

package main

import (
 "fmt"
)

func main() {
 s := "Hello"
 i := 123

 t := fmt.Sprintf("%s%d", s, i)

 fmt.Println(t)
}

Hello123


fn main() {
    let s = "Foo";
    let i = 1;
    let t = format!("{}{}", s, i);
    
    println!("{}" , t);
}

Foo1


154. Halfway between two hex color codes

Find color c, the average between colors c1, c2.
c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # . Assume linear computations, ignore gamma corrections.

求两个十六进制颜色代码的中间值

package main

import (
 "fmt"
 "strconv"
 "strings"
)

// For concision, halfway assume valid inputs.
// Caller must have explicitly checked that c1, c2 are well-formed color codes.
func halfway(c1, c2 string) string {
 r1, _ := strconv.ParseInt(c1[1:3], 160)
 r2, _ := strconv.ParseInt(c2[1:3], 160)
 r := (r1 + r2) / 2

 g1, _ := strconv.ParseInt(c1[3:5], 160)
 g2, _ := strconv.ParseInt(c2[3:5], 160)
 g := (g1 + g2) / 2

 b1, _ := strconv.ParseInt(c1[5:7], 160)
 b2, _ := strconv.ParseInt(c2[5:7], 160)
 b := (b1 + b2) / 2

 c := fmt.Sprintf("#%02X%02X%02X", r, g, b)
 return c
}

func main() {
 c1 := "#15293E"
 c2 := "#012549"

 if err := checkFormat(c1); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c1, err))
 }
 if err := checkFormat(c2); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c2, err))
 }

 c := halfway(c1, c2)
 fmt.Println("The average of", c1, "and", c2, "is", c)
}

func checkFormat(color string) error {
 if len(color) != 7 {
  return fmt.Errorf("Hex colors have exactly 7 chars")
 }
 if color[0] != '#' {
  return fmt.Errorf("Hex colors start with #")
 }
 isNotDigit := func(c rune) bool { return (c < '0' || c > '9') && (c < 'a' || c > 'f') }
 if strings.IndexFunc(strings.ToLower(color[1:]), isNotDigit) != -1 {
  return fmt.Errorf("Forbidden char")
 }
 return nil
}

The average of #15293E and #012549 is #0B2743

package main

import (
 "fmt"
 "strconv"
 "strings"
)

// For concision, halfway assume valid inputs.
// Caller must have explicitly checked that c1, c2 are well-formed color codes.
func halfway(c1, c2 string) string {
 var buf [7]byte
 buf[0] = '#'
 for i := 0; i < 3; i++ {
  sub1 := c1[1+2*i : 3+2*i]
  sub2 := c2[1+2*i : 3+2*i]
  v1, _ := strconv.ParseInt(sub1, 160)
  v2, _ := strconv.ParseInt(sub2, 160)
  v := (v1 + v2) / 2
  sub := fmt.Sprintf("%02X", v)
  copy(buf[1+2*i:3+2*i], sub)
 }
 c := string(buf[:])

 return c
}

func main() {
 c1 := "#15293E"
 c2 := "#012549"

 if err := checkFormat(c1); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c1, err))
 }
 if err := checkFormat(c2); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c2, err))
 }

 c := halfway(c1, c2)
 fmt.Println("The average of", c1, "and", c2, "is", c)
}

func checkFormat(color string) error {
 if len(color) != 7 {
  return fmt.Errorf("Hex colors have exactly 7 chars")
 }
 if color[0] != '#' {
  return fmt.Errorf("Hex colors start with #")
 }
 isNotDigit := func(c rune) bool { return (c < '0' || c > '9') && (c < 'a' || c > 'f') }
 if strings.IndexFunc(strings.ToLower(color[1:]), isNotDigit) != -1 {
  return fmt.Errorf("Forbidden char")
 }
 return nil
}

The average of #15293E and #012549 is #0B2743


use std::str::FromStr;
use std::fmt;

#[derive(Debug)]
struct Colour {
    r: u8,
    g: u8,
    b: u8
}

#[derive(Debug)]
enum ColourError {
    MissingHash,
    InvalidRed,
    InvalidGreen,
    InvalidBlue
}

impl fmt::Display for Colour {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "#{:02x}{:02x}{:02x}"self.r, self.g, self.b)
    }
}

impl FromStr for Colour {
    type Err = ColourError;
    
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !s.starts_with('#') {
            Err(ColourError::MissingHash)
        } else {
            Ok(Colour {
                r: u8::from_str_radix(&s[1..3], 16).map_err(|_| ColourError::InvalidRed)?,
                g: u8::from_str_radix(&s[3..5], 16).map_err(|_| ColourError::InvalidGreen)?,
                b: u8::from_str_radix(&s[5..7], 16).map_err(|_| ColourError::InvalidBlue)?
            })
        }
    }
}

fn mid_colour(c1: &str, c2: &str) -> Result<String, ColourError> {
    let c1 = c1.parse::<Colour>()?;
    let c2 = c2.parse::<Colour>()?;
    let c = Colour {
        r: (((c1.r as u16) + (c2.r as u16))/2as u8,
        g: (((c1.g as u16) + (c2.g as u16))/2as u8,
        b: (((c1.b as u16) + (c2.b as u16))/2as u8
    };
    Ok(format!("{}", c))
}

fn main() {
    println!("{}", mid_colour("#15293E""#012549").unwrap())
}

#0b2743


155. Delete file

Delete from filesystem the file having path filepath.

删除文件

package main

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

func main() {
 for _, filepath := range []string{
  "/tmp/foo.txt",
  "/tmp/bar.txt",
  "/tmp/foo.txt",
 } {
  err := os.Remove(filepath)
  if err == nil {
   fmt.Println("Removed", filepath)
  } else {
   fmt.Fprintln(os.Stderr, err)
  }
 }
}

func init() {
 err := ioutil.WriteFile("/tmp/foo.txt", []byte(`abc`), 0644)
 if err != nil {
  panic(err)
 }
}
Removed /tmp/foo.txt
remove /tmp/bar.txt: no such file or directory
remove /tmp/foo.txt: no such file or directory

use std::fs;

fn main() {
    let filepath = "/tmp/abc";

    println!("Creating {}", filepath);
    let _file = fs::File::create(filepath);

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

    println!("Deleting {}", filepath);
    let r = fs::remove_file(filepath);
    println!("{:?}", r);

    let b = std::path::Path::new(filepath).exists();
    println!("{} exists: {}", filepath, b);
}
Creating /tmp/abc
/tmp/abc exists: true
Deleting /tmp/abc
Ok(())
/tmp/abc exists: false

156. Format integer with zero-padding

Assign to string s the value of integer i in 3 decimal digits. Pad with zeros if i < 100. Keep all digits if i ≥ 1000.

用零填充格式化整数

package main

import (
 "fmt"
)

func main() {
 for _, i := range []int{
  0,
  8,
  64,
  256,
  2048,
 } {
  s := fmt.Sprintf("%03d", i)
  fmt.Println(s)
 }
}

000
008
064
256
2048

fn main() {
    let i = 1;
    let s = format!("{:03}", i);
    
    println!("{}", s);
    
    
    let i = 1000;
    let s = format!("{:03}", i);
    
    println!("{}", s);
}
001
1000

157. Declare constant string

Initialize a constant planet with string value "Earth".

声明常量字符串

package main

import (
 "fmt"
)

const planet = "Earth"

func main() {
 fmt.Println("We live on planet", planet)
}

We live on planet Earth


fn main() {
    const PLANET: &str = "Earth";
    
    println!("{}", PLANET);
}

Earth


158. Random sublist

Create a new list y from randomly picking exactly k elements from list x.

It is assumed that x has at least k elements. Each element must have same probability to be picked. Each element from x must be picked at most once. Explain if the original ordering is preserved or not.

随机子列表

package main

import (
 "fmt"
 "math/rand"
)

func main() {
 type T string

 x := []T{"Alice""Bob""Carol""Dan""Eve""Frank""Grace""Heidi"}
 k := 4

 y := make([]T, k)
 perm := rand.Perm(len(x))
 for i, v := range perm[:k] {
  y[i] = x[v]
 }

 fmt.Printf("%q", y)
}

["Frank" "Eve" "Carol" "Grace"]


use rand::prelude::*;
let mut rng = &mut rand::thread_rng();
let y = x.choose_multiple(&mut rng, k).cloned().collect::<Vec<_>>();

159. Trie

Define a Trie data structure, where entries have an associated value. (Not all nodes are entries)

前缀树/字典树

package main

import (
 "fmt"
 "unicode/utf8"
)

type Trie struct {
 c        rune
 children map[rune]*Trie
 isLeaf   bool
 value    V
}

type V int

func main() {
 t := NewTrie(0)
 for s, v := range map[string]V{
  "to":  7,
  "tea"3,
  "ted"4,
  "ten"12,
  "A":   15,
  "i":   11,
  "in":  5,
  "inn"9,
 } {
  t.insert(s, v)
 }
 fmt.Println(t.startsWith("te"""))
}

func NewTrie(c rune) *Trie {
 t := new(Trie)
 t.c = c
 t.children = map[rune]*Trie{}
 return t
}

func (t *Trie) insert(s string, value V) {
 if s == "" {
  t.isLeaf = true
  t.value = value
  return
 }
 c, tail := cut(s)
 child, exists := t.children[c]
 if !exists {
  child = NewTrie(c)
  t.children[c] = child
 }
 child.insert(tail, value)
}

func (t *Trie) startsWith(p string, accu string) []string {
 if t == nil {
  return nil
 }
 if p == "" {
  var result []string
  if t.isLeaf {
   result = append(result, accu)
  }
  for c, child := range t.children {
   rec := child.startsWith("", accu+string(c))
   result = append(result, rec...)
  }
  return result
 }
 c, tail := cut(p)
 return t.children[c].startsWith(tail, accu+string(c))
}

func cut(s string) (head rune, tail string) {
 r, size := utf8.DecodeRuneInString(s)
 return r, s[size:]
}

[ten tea ted]


struct Trie {
    val: String,
    nodes: Vec<Trie>
}

160. Detect if 32-bit or 64-bit architecture

Execute f32() if platform is 32-bit, or f64() if platform is 64-bit.
This can be either a compile-time condition (depending on target) or a runtime detection.

检测是32位还是64位架构

package main

import (
 "fmt"
 "strconv"
)

func main() {
 if strconv.IntSize == 32 {
  f32()
 }
 if strconv.IntSize == 64 {
  f64()
 }
}

func f32() {
 fmt.Println("I am 32-bit")
}

func f64() {
 fmt.Println("I am 64-bit")
}

I am 64-bit


fn main() {
    match std::mem::size_of::<&char>() {
        4 => f32(),
        8 => f64(),
        _ => {}
    }
}

fn f32() {
    println!("I am 32-bit");
}

fn f64() {
    println!("I am 64-bit");
}

I am 64-bit


参考资料

[1]

Golang vs. Rust: Which Programming Language To Choose in 2023?: https://www.trio.dev/blog/golang-vs-rust

本文由 mdnice 多平台发布

相关文章:

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

题目来自 Golang vs. Rust: Which Programming Language To Choose in 2023?[1] 141. Iterate in sequence over two lists Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element. 依次迭代两个列表 依次迭代列表项1…...

pytorch学习-线性神经网络——softmax回归+损失函数+图片分类数据集

1.softmax回归 Softmax回归&#xff08;Softmax Regression&#xff09;是一种常见的多分类模型&#xff0c;可以用于将输入变量映射到多个类别的概率分布中。softmax回归是机器学习中非常重要并且经典的模型&#xff0c;虽然叫回归&#xff0c;实际上是一个分类问题 1.1分类与…...

Docker compose(容器编排)

Docker compose&#xff08;容器编排&#xff09; 一、安装Docker compose 1.安装Docker compose Docker Compose 环境安装 Docker Compose 是 Docker 的独立产品&#xff0c;因此需要安装 Docker 之后在单独安装 Docker Compose#下载 curl -L https://github.com/docker/co…...

xmind latex【记录备忘】

xmind latex 换行 换行必须要有\begin{align}和\end{align}&#xff0c;此时再在里面用\才能换行&#xff0c;如果只写112\224是不能换行的...

RocketMQ(1.NameServer源码)

NameServer功能简述 主要功能如下 服务注册与发现&#xff1a;Nameserver扮演了RocketMQ集群中服务注册中心的角色。当RocketMQ中的Broker、Producer和Consumer启动时&#xff0c;它们会向Nameserver注册自己的网络地址和角色信息。Nameserver维护着集群中所有活跃实例的信息…...

责任链vs金融登录

金融app相对普通app而言&#xff0c;出于安全考虑&#xff0c;其安全校验方式比较多&#xff0c;以某些银行app为例&#xff0c;手机号登录成功后&#xff0c;会增加指纹、手势、OCR人脸等验证&#xff01;这些安全项的校验&#xff0c;会根据用户的风险等级有不同的校验优先级…...

通过VIOOVI,了解联合作业分析的意义和目标!

现如今企业的主流生产模式就是流水线生产&#xff0c;一道工序结束后&#xff0c;紧接着开展下一项工序&#xff0c;这种作业模式可以以一种比较高效的方式缩减生产时间。尽管流水作业的效率已经够高的了&#xff0c;但是各个工序之间如果衔接不到位的话&#xff0c;会造成生产…...

清洁机器人规划控制方案

清洁机器人规划控制方案 作者联系方式Forrest709335543qq.com 文章目录 清洁机器人规划控制方案方案简介方案设计模块链路坐标变换算法框架 功能设计定点自主导航固定路线清洁区域覆盖清洁贴边沿墙清洁自主返航回充 仿真测试仿真测试准备定点自主导航测试固定路线清洁测试区域…...

设计模式 - 工厂模式

一、 简单工厂&#xff08;Simple Factory Pattern&#xff09; 1、概念 一个工厂对象决定创建出哪一种产品类的实力&#xff0c;但不属于GOF23种设计模式。 简单工厂适用于工厂类负责创建的对象较少的场景&#xff0c;且客户端只需要传入工厂类的参数&#xff0c;对于如何创…...

elementUI this.$confirm 文字大小样式

dangerouslyUseHTMLString:true // message部分 以html片段处理 customClass //MessageBox 的自定义类名 整个comfirm框自定义类名 cancelButtonClass // 取消按钮的自定义类名 confirmButtonClass // 确定按钮的自定义类名<style> .addcomfirm{width: 500px; } .a…...

Kafka的TimingWheel

Kafka的TimingWheel是Kafka中的一个时间轮实现,用于管理和处理延迟消息。时间轮是一种定时器的数据结构,可以高效地管理和触发定时事件。 在Kafka中,TimingWheel用于处理延迟消息的重试。当Kafka生产者发送消息到Kafka集群,但由于某些原因导致消息发送失败,生产者会将这些…...

第2集丨webpack 江湖 —— 创建一个简单的webpack工程demo

目录 一、创建webpack工程1.1 新建 webpack工程目录1.2 项目初始化1.3 新建src目录和文件1.4 安装jQuery1.5 安装webpack1.6 配置webpack1.6.1 创建配置文件&#xff1a;webpack.config.js1.6.2 配置dev脚本1.7 运行dev脚本 1.8 查看效果1.9 附件1.9.1 package.json1.9.2 webpa…...

Python(Web时代)——初识flask

flask简介 介绍 Flask是一个用Python编写的Web 微框架&#xff0c;让我们可以使用Python语言快速实现一个网站或Web服务。它是BSD授权的&#xff0c;一个有少量限制的免费软件许可。它使用了 Werkzeug 工具箱和 Jinja2 模板引擎。 Flask 的设计理念是简单、灵活、易于扩展&a…...

二、SQL-5.DQL-8).案例练习

1、查询年龄为20,21,22,23岁的员工信息 select * from emp where age in(20, 21, 22, 23) and gender 女; 2、查询性别为男&#xff0c;并且年龄在20-40岁&#xff08;含&#xff09;以内的姓名为三个字的员工 select * from emp where gender 男 && age between 2…...

浙大数据结构第五周之05-树7 堆中的路径

题目详情&#xff1a; 将一系列给定数字依次插入一个初始为空的小顶堆H[]。随后对任意给定的下标i&#xff0c;打印从H[i]到根结点的路径。 输入格式: 每组测试第1行包含2个正整数N和M(≤1000)&#xff0c;分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间[-1…...

C# Modbus TCP上位机测试

前面说了三菱和西门子PLC的上位机通信&#xff0c;实际在生产应用中&#xff0c;设备会有很多不同的厂家生产的PLC&#xff0c;那么&#xff0c;我们就需要一种通用的语言&#xff0c;进行设备之间的通信&#xff0c;工业上较为广泛使用的语言之一就是Modbus。 Modbus有多种连…...

instr字符查找函数(oracle用instr来代替like)

instr函数&#xff1a;字符查找函数。其功能是查找一个字符串在另一个字符串中首次出现的位置。 instr函数在Oracle/PLSQL中是返回要截取的字符串在源字符串中的位置。 语法 instr( string1, string2, start_position,nth_appearance ) 参数 string1&#xff1a;源字符串&am…...

trie树的一点理解

这个是最简单的数据结构&#xff1a;因为只需要记住两句话就能完美的写出简洁优雅的代码 1. 每次都是从根节点开始看(或者说从第零次插入的东西开始遍历&#xff0c;son[][]里面存的是第几次插入) 2每次遍历都是插入和查询的字符串 #include<iostream> using namespace …...

Linux CentOS监控系统的运行情况工具 - top/htop/glances/sar/nmon

在CentOS系统中&#xff0c;您可以使用以下工具来监控系统的运行情况&#xff1a; 1. top&#xff1a; top 是一个命令行工具&#xff0c;用于实时监控系统的进程、CPU、内存和负载情况。您可以使用以下命令来启动 top&#xff1a; top 输出 2. htop&#xff1a; htop 是一…...

Qt开发(2)——windows下调用外部程序

一、QProcess::start &#xff11;&#xff0e;阻塞性 start是非阻塞函数&#xff0c;但是这里的waitForFinished是阻塞的 2. 调用外部压缩程序7z // 目标压缩路径 QString zipFilePath destinationFolder "/" zipFileName; QStringList arguments{"a&qu…...

R语言AI模型部署方案:精准离线运行详解

R语言AI模型部署方案:精准离线运行详解 一、项目概述 本文将构建一个完整的R语言AI部署解决方案,实现鸢尾花分类模型的训练、保存、离线部署和预测功能。核心特点: 100%离线运行能力自包含环境依赖生产级错误处理跨平台兼容性模型版本管理# 文件结构说明 Iris_AI_Deployme…...

Cinnamon修改面板小工具图标

Cinnamon开始菜单-CSDN博客 设置模块都是做好的&#xff0c;比GNOME简单得多&#xff01; 在 applet.js 里增加 const Settings imports.ui.settings;this.settings new Settings.AppletSettings(this, HTYMenusonichy, instance_id); this.settings.bind(menu-icon, menu…...

苍穹外卖--缓存菜品

1.问题说明 用户端小程序展示的菜品数据都是通过查询数据库获得&#xff0c;如果用户端访问量比较大&#xff0c;数据库访问压力随之增大 2.实现思路 通过Redis来缓存菜品数据&#xff0c;减少数据库查询操作。 缓存逻辑分析&#xff1a; ①每个分类下的菜品保持一份缓存数据…...

土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等

&#x1f50d; 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术&#xff0c;可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势&#xff0c;还能有效评价重大生态工程…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...

20个超级好用的 CSS 动画库

分享 20 个最佳 CSS 动画库。 它们中的大多数将生成纯 CSS 代码&#xff0c;而不需要任何外部库。 1.Animate.css 一个开箱即用型的跨浏览器动画库&#xff0c;可供你在项目中使用。 2.Magic Animations CSS3 一组简单的动画&#xff0c;可以包含在你的网页或应用项目中。 3.An…...

【C++特殊工具与技术】优化内存分配(一):C++中的内存分配

目录 一、C 内存的基本概念​ 1.1 内存的物理与逻辑结构​ 1.2 C 程序的内存区域划分​ 二、栈内存分配​ 2.1 栈内存的特点​ 2.2 栈内存分配示例​ 三、堆内存分配​ 3.1 new和delete操作符​ 4.2 内存泄漏与悬空指针问题​ 4.3 new和delete的重载​ 四、智能指针…...

NPOI操作EXCEL文件 ——CAD C# 二次开发

缺点:dll.版本容易加载错误。CAD加载插件时&#xff0c;没有加载所有类库。插件运行过程中用到某个类库&#xff0c;会从CAD的安装目录找&#xff0c;找不到就报错了。 【方案2】让CAD在加载过程中把类库加载到内存 【方案3】是发现缺少了哪个库&#xff0c;就用插件程序加载进…...

从面试角度回答Android中ContentProvider启动原理

Android中ContentProvider原理的面试角度解析&#xff0c;分为​​已启动​​和​​未启动​​两种场景&#xff1a; 一、ContentProvider已启动的情况 1. ​​核心流程​​ ​​触发条件​​&#xff1a;当其他组件&#xff08;如Activity、Service&#xff09;通过ContentR…...

基于鸿蒙(HarmonyOS5)的打车小程序

1. 开发环境准备 安装DevEco Studio (鸿蒙官方IDE)配置HarmonyOS SDK申请开发者账号和必要的API密钥 2. 项目结构设计 ├── entry │ ├── src │ │ ├── main │ │ │ ├── ets │ │ │ │ ├── pages │ │ │ │ │ ├── H…...