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

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


21. Swap values

交换变量a和b的值

a, b = b, a
package main

import "fmt"

func main() {
 a := 3
 b := 10
 a, b = b, a
 fmt.Println(a)
 fmt.Println(b)
}
10
3

fn main() {
    let a = 3;
    let b = 10;

    let (a, b) = (b, a);

    println!("a: {a}, b: {b}", a=a, b=b);
}

输出

a: 10, b: 3

or

fn main() {
    let (a, b) = (1242);
    
    println!("a = {}, b = {}", a, b);
    
    let (a, b) = (b, a);
    
    println!("a = {}, b = {}", a, b);
}

输出

a = 12, b = 42
a = 42, b = 12

22. Convert string to integer

将字符串转换为整型

import "strconv"
i, err  := strconv.Atoi(s) 
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 // create a string
 s := "123"
 fmt.Println(s)
 fmt.Println("type:", reflect.TypeOf(s))

 // convert string to int
 i, err := strconv.Atoi(s)
 if err != nil {
  panic(err)
 }
 fmt.Println(i)
 fmt.Println("type:", reflect.TypeOf(i))
}
123
typestring
123
typeint

or

import "strconv"
i, err := strconv.ParseInt(s, 100)
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 s := "123"
 fmt.Println("s is", reflect.TypeOf(s), s)

 i, err := strconv.ParseInt(s, 100)
 if err != nil {
  panic(err)
 }

 fmt.Println("i is", reflect.TypeOf(i), i)
}

s is string 123
i is int64 123

fn main() {
    // This prints 123
    let mut s = "123";
    let mut i = s.parse::<i32>().unwrap();
    println!("{:?}", i);

    // This panics
    s = "12u3";
    i = s.parse::<i32>().unwrap();
    println!("{:?}", i);
}

输出

123
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:860
note: Run with `RUST_BACKTRACE=1for a backtrace.

or

fn main() {
    let mut s = "123";
    let mut i: i32 = s.parse().unwrap_or(0);
    println!("{:?}", i);

    s = "12u3";
    i = s.parse().unwrap_or(0);
    println!("{:?}", i);
}

输出

123
0

or

fn main() {
    let mut s = "123";
    let mut i = match s.parse::<i32>() {
        Ok(i) => i,
        Err(_e) => -1,
    };
    println!("{:?}", i);

    s = "12u3";
    i = match s.parse::<i32>() {
        Ok(i) => i,
        Err(_e) => -1,
    };
    println!("{:?}", i);
}

输出

123
-1

23. Convert real number to string with 2 decimal places

Given a real number x, create its string representation s with 2 decimal digits following the dot.

给定一个实数,小数点后保留两位小数

package main

import "fmt"

func main() {
 x := 3.14159
 s := fmt.Sprintf("%.2f", x)
 fmt.Println(s)
}

输出

3.14


fn main() {
    let x = 42.1337;
    let s = format!("{:.2}", x);
    
    println!("{}", s);
}

输出

42.13


24. Assign to string the japanese word ネコ

Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)

声明一个新的字符串s,并用文字值“ネコ”初始化它(在日语中是“cat”的意思)

package main

import "fmt"

func main() {
 s := "ネコ"
 fmt.Println(s)
}


fn main() {
    let s = "ネコ";
    println!("{}", s);
}

25. Send a value to another thread

Share the string value "Alan" with an existing running process which will then display "Hello, Alan"

将字符串值“Alan”与现有的正在运行的进程共享,该进程将显示“你好,Alan”

ch <- "Alan"
package main

import (
 "fmt"
 "time"
)

func main() {
 ch := make(chan string)

 go func() {
  v := <-ch
  fmt.Printf("Hello, %v\n", v)
 }()

 ch <- "Alan"

 // Make sure the non-main goroutine had the chance to finish.
 time.Sleep(time.Second)
}

Hello, Alan

The receiver goroutine blocks reading the string channel ch. The current goroutine sends the value to ch. A goroutine is like a thread, but more lightweight.


use std::thread;
use std::sync::mpsc::channel;

fn main() {
    let (send, recv) = channel();

    let handle = thread::spawn(move || loop {
        let msg = recv.recv().unwrap();
        println!("Hello, {:?}", msg);
    });

    send.send("Alan").unwrap();
    
    handle.join().unwrap();
}

输出 Hello, "Alan"


26. Create a 2-dimensional array

Declare and initialize a matrix x having m rows and n columns, containing real numbers.

创建一个二维数组

声明并初始化一个有m行n列的矩阵x,包含实数。

const m, n = 34
var x [m][n]float64
package main

import "fmt"

func main() {
 const m, n = 34
 var x [m][n]float64

 x[1][2] = 8
 fmt.Println(x)
}

[[0 0 0 0] [0 0 8 0] [0 0 0 0]]

or

package main

import "fmt"

func main() {
 x := make2D(23)

 x[1][1] = 8
 fmt.Println(x)
}

func make2D(m, n int) [][]float64 {
 buf := make([]float64, m*n)

 x := make([][]float64, m)
 for i := range x {
  x[i] = buf[:n:n]
  buf = buf[n:]
 }
 return x
}

[[0 0 0] [0 8 0]]


fn main() {
    const M: usize = 4;
    const N: usize = 6;

    let x = vec![vec![0.0f64; N]; M];
    
    println!("{:#?}", x);
}

输出

[
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ],
]
fn main() {
  const M: usize = 3;
  const N: usize = 4;

  let mut x = [[0.0; N] ; M];

  x[1][3] = 5.0;
  println!("{:#?}", x);
}

输出

[
    [
        0.0,
        0.0,
        0.0,
        0.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        5.0,
    ],
    [
        0.0,
        0.0,
        0.0,
        0.0,
    ],
]

27. Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

创建一个三维数组

声明并初始化一个三维数组x,它有m,n,p维边界,并且包含实数。

const m, n, p = 223
var x [m][n][p]float64
package main

import "fmt"

func main() {
 const m, n, p = 223
 var x [m][n][p]float64

 x[1][0][2] = 9

 // Value of x
 fmt.Println(x)

 // Type of x
 fmt.Printf("%T", x)
}
[[[0 0 0] [0 0 0]] [[0 0 9] [0 0 0]]]
[2][2][3]float64

or

func make3D(m, n, p int) [][][]float64 {
 buf := make([]float64, m*n*p)

 x := make([][][]float64, m)
 for i := range x {
  x[i] = make([][]float64, n)
  for j := range x[i] {
   x[i][j] = buf[:p:p]
   buf = buf[p:]
  }
 }
 return x
}
package main

import "fmt"

func main() {
 x := make3D(223)

 x[1][0][2] = 9
 fmt.Println(x)
}

func make3D(m, n, p int) [][][]float64 {
 buf := make([]float64, m*n*p)

 x := make([][][]float64, m)
 for i := range x {
  x[i] = make([][]float64, n)
  for j := range x[i] {
   x[i][j] = buf[:p:p]
   buf = buf[p:]
  }
 }
 return x
}
[[[0 0 0] [0 0 0]] [[0 0 9] [0 0 0]]]

fn main() {
    let m = 4;
    let n = 6;
    let p = 2;

    let x = vec![vec![vec![0.0f64; p]; n]; m];
    
    println!("{:#?}", x);
}

输出


[
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
]
fn main() {
    const M: usize = 4;
    const N: usize = 6;
    const P: usize = 2;

    let x = [[[0.0f64; P]; N]; M];

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

输出

[
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
    [
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
        [
            0.0,
            0.0,
        ],
    ],
]

28. Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

按x->p的升序对类似数组的集合项的元素进行排序,其中p是项中对象的项类型的字段。

package main

import "fmt"
import "sort"

type Item struct {
 label string
 p     int
 lang  string
}

type ItemPSorter []Item

func (s ItemPSorter) Len() int           { return len(s) }
func (s ItemPSorter) Less(i, j int) bool { return s[i].p < s[j].p }
func (s ItemPSorter) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

func sortItems(items []Item) {
 sorter := ItemPSorter(items)
 sort.Sort(sorter)
}

func main() {
 items := []Item{
  {"twelve"12"english"},
  {"six"6"english"},
  {"eleven"11"english"},
  {"zero"0"english"},
  {"two"2"english"},
 }
 fmt.Println("Unsorted: ", items)
 sortItems(items)
 fmt.Println("Sorted: ", items)
}

Unsorted:  [{twelve 12 english} {six 6 english} {eleven 11 english} {zero 0 english} {two 2 english}]
Sorted:  [{zero 0 english} {two 2 english} {six 6 english} {eleven 11 english} {twelve 12 english}]

or

package main

import "fmt"
import "sort"

type Item struct {
 label string
 p     int
 lang  string
}

func main() {
 items := []Item{
  {"twelve"12"english"},
  {"six"6"english"},
  {"eleven"11"english"},
  {"zero"0"english"},
  {"two"2"english"},
 }
 fmt.Println("Unsorted: ", items)

 less := func(i, j int) bool {
  return items[i].p < items[j].p
 }
 sort.Slice(items, less)

 fmt.Println("Sorted: ", items)
}

Unsorted:  [{twelve 12 english} {six 6 english} {eleven 11 english} {zero 0 english} {two 2 english}]
Sorted:  [{zero 0 english} {two 2 english} {six 6 english} {eleven 11 english} {twelve 12 english}]

#[derive(Debug)]
struct Foo {
    p: i32,
}

fn main() {
    let mut items = vec![Foo { p: 3 }, Foo { p: 1 }, Foo { p: 2 }, Foo { p: 4 }];

    items.sort_by(|a, b| a.p.cmp(&b.p));

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

输出

[Foo { p: 1 }, Foo { p: 2 }, Foo { p: 3 }, Foo { p: 4 }]

or

#[derive(Debug)]
struct Foo {
    p: i32,
}

fn main() {
    let mut items = vec![Foo { p: 3 }, Foo { p: 1 }, Foo { p: 2 }, Foo { p: 4 }];

    items.sort_by_key(|x| x.p);

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

输出

[Foo { p: 1 }, Foo { p: 2 }, Foo { p: 3 }, Foo { p: 4 }]

29. Remove item from list, by its index

Remove i-th item from list items. This will alter the original list or return a new list, depending on which is more idiomatic. Note that in most languages, the smallest valid value for i is 0.

从列表项中删除第I项。 这将改变原来的列表或返回一个新的列表,这取决于哪个更习惯。 请注意,在大多数语言中,I的最小有效值是0。

package main

import (
 "fmt"
)

func main() {
 items := []string{"a""b""c""d""e""f"}
 fmt.Println(items)

 i := 2
 items = append(items[:i], items[i+1:]...)
 fmt.Println(items)
}
[a b c d e f]
[a b d e f]

or

copy(items[i:], items[i+1:])
items[len(items)-1] = nil
items = items[:len(items)-1]

fn main() {
    let mut v = vec![123];
    assert_eq!(v.remove(1), 2);
    assert_eq!(v, [13]);
    
}

30. Parallelize execution of 1000 independent tasks

Launch the concurrent execution of procedure f with parameter i from 1 to 1000. Tasks are independent and f(i) doesn't return any value. Tasks need not run all at the same time, so you may use a pool.

用参数I从1到1000启动程序f的并发执行。 任务是独立的,f(i)不返回值。 任务不需要同时运行,所以可以使用pools

import "sync"
wg := sync.WaitGroup{}
wg.Add(1000)
for i := 1; i <= 1000; i++ {
 go func(j int) {
          f(j)
          wg.Done()
        }(i)
}
wg.Wait()
package main

import (
 "fmt"
 "math/rand"
 "time"
)

func f(i int) {
 d := rand.Int() % 10000
 time.Sleep(time.Duration(d))
 fmt.Printf("Hello %v\n", i)
}

func main() {
 for i := 1; i <= 1000; i++ {
  go f(i)
 }

 time.Sleep(4 * time.Second)
}


use std::thread;

fn main() {
    let threads: Vec<_> = (0..1000).map(|i| thread::spawn(move || f(i))).collect();

    for thread in threads {
        thread.join();
    }
}

fn f(i: i32) {
    println!("{}", i);
}

or

extern crate rayon;

use rayon::prelude::*;

fn main() {
    (0..1000).into_par_iter().for_each(f);
}

fn f(i: i32) {
    println!("{}", i);
}

31. Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

创建递归函数f,该函数返回从f(i-1)计算的非负整数I的阶乘

func f(i int) int {
  if i == 0 {
    return 1
  }
  return i * f(i-1)
}
package main

import (
 "fmt"
)

func f(i int) int {
 if i == 0 {
  return 1
 }
 return i * f(i-1)
}

func main() {
 for i := 0; i <= 10; i++ {
  fmt.Printf("f(%d) = %d\n", i, f(i))
 }
}

输出

f(0) = 1
f(1) = 1
f(2) = 2
f(3) = 6
f(4) = 24
f(5) = 120
f(6) = 720
f(7) = 5040
f(8) = 40320
f(9) = 362880
f(10) = 3628800

fn f(n: u32) -> u32 {
    if n < 2 {
        1
    } else {
        n * f(n - 1)
    }
}

fn main() {
    println!("{}", f(4 as u32));
}

输出

24

or

fn factorial(num: u64) -> u64 {
    match num {
        0 | 1=> 1,
        _ => factorial(num - 1) * num,
    }
}

fn main (){
    println!("{}", factorial(0));
    println!("{}", factorial(1));
    println!("{}", factorial(2));
    println!("{}", factorial(3));
    println!("{}", factorial(4));
    println!("{}", factorial(5));
}

输出

1
1
2
6
24
120

32. Integer exponentiation by squaring

Create function exp which calculates (fast) the value x power n. x and n are non-negative integers.

创建函数exp,计算(快速)x次方n的值。 x和n是非负整数。

package main

import "fmt"

func exp(x, n int) int {
 switch {
 case n == 0:
  return 1
 case n == 1:
  return x
 case n%2 == 0:
  return exp(x*x, n/2)
 default:
  return x * exp(x*x, (n-1)/2)
 }
}

func main() {
 fmt.Println(exp(35))
}

输出

243


fn exp(x: u64, n: u64) -> u64 {
    match n {
        0 => 1,
        1 => x,
        i if i % 2 == 0 => exp(x * x, n / 2),
        _ => x * exp(x * x, (n - 1) / 2),
    }
}

fn main() {
    let x = 16;
    let n = 4;
    
    println!("{}", exp(x, n));
}

输出

65536


33. Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

为变量x分配新值f(x),确保在读和写之间没有其他线程可以修改x。

package main

import (
 "fmt"
 "sync"
)

func main() {
 var lock sync.RWMutex
 x := 3

 lock.Lock()
 x = f(x)
 lock.Unlock()

 fmt.Println(x)
}

func f(i int) int {
 return 2 * i
}

6


use std::sync::Mutex;

fn f(x: i32) -> i32 {
    x + 1
}

fn main() {
    let x = Mutex::new(0);
    let mut x = x.lock().unwrap();
    *x = f(*x);
    
    println!("{:?}", *x);
}

输出

1


34. Create a set of objects

Declare and initialize a set x containing objects of type T.

声明并初始化一个包含t类型对象的集合x。

x := make(map[T]bool)
package main

import "fmt"

type T string

func main() {
 // declare a Set (implemented as a map)
 x := make(map[T]bool)

 // add some elements
 x["A"] = true
 x["B"] = true
 x["B"] = true
 x["C"] = true
 x["D"] = true

 // remove an element
 delete(x, "C")

 for t, _ := range x {
  fmt.Printf("x contains element %v \n", t)
 }
}
x contains element D 
x contains element A 
x contains element B 

or

x := make(map[T]struct{})
package main

import "fmt"

type T string

func main() {
 // declare a Set (implemented as a map)
 x := make(map[T]struct{})

 // add some elements
 x["A"] = struct{}{}
 x["B"] = struct{}{}
 x["B"] = struct{}{}
 x["C"] = struct{}{}
 x["D"] = struct{}{}

 // remove an element
 delete(x, "C")

 for t, _ := range x {
  fmt.Printf("x contains element %v \n", t)
 }
}
x contains element B 
x contains element D 
x contains element A 

use std::collections::HashSet;

fn main() {
    let mut m = HashSet::new();
    m.insert("a");
    m.insert("b");

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

输出

{"a""b"}

35. First-class function : compose

Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns composition function g ∘ f

用参数f (A -> B)和g (B -> C)实现一个函数compose (A -> C),返回composition函数g ∘ f

package main

import "fmt"
import "strconv"

func compose(f func(A) Bg func(B) Cfunc(A) C {
 return func(x A) C {
  return g(f(x))
 }
}

func main() {
 squareFromStr := compose(str2int, square)
 fmt.Println(squareFromStr("12"))
}

type A string
type B int
type C int

func str2int(a A) B {
 b, _ := strconv.ParseInt(string(a), 1032)
 return B(b)
}

func square(b B) C {
 return C(b * b)
}

144


fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
 where F: 'a + Fn(A) -> B, G: 'a + Fn(B) -> C
{
 Box::new(move |x| g(f(x)))
}

or

fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
 move |x| g(f(x))
}

fn main() {
    let f = |x: u32| (x * 2as i32;
    let g = |x: i32| (x + 1as f32;
    let c = compose(f, g);
    
    println!("{}", c(2));
}

输出

5


36. First-class function : generic composition

Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.

实现一个函数组合,该函数组合为任何恰好有1个参数的函数f和g返回组合函数g ∘ f。

package main

import "fmt"

func composeIntFuncs(f func(int) intg func(int) intfunc(int) int {
 return func(x int) int {
  return g(f(x))
 }
}

func main() {
 double := func(x int) int {
  return 2 * x
 }
 addTwo := func(x int) int {
  return x + 2
 }
 h := composeIntFuncs(double, addTwo)

 for i := 0; i < 10; i++ {
  fmt.Println(i, h(i), addTwo(double(i)))
 }
}
0 2 2
1 4 4
2 6 6
3 8 8
4 10 10
5 12 12
6 14 14
7 16 16
8 18 18
9 20 20

fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
 where F: 'a + Fn(A) -> B, G: 'a + Fn(B) -> C
{
 Box::new(move |x| g(f(x)))
}

or

fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
 move |x| g(f(x))
}

fn main() {
    let f = |x: u32| (x * 2as i32;
    let g = |x: i32| (x + 1as f32;
    let c = compose(f, g);
    
    println!("{}", c(2));
}

输出

5


37. Currying

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

将一个接受多个参数的函数转换为一个预设了某些参数的函数。

package main

import (
 "fmt"
 "time"
)

type Company string

type Employee struct {
 FirstName string
 LastName  string
}

func (e *Employee) String() string {
 return "<" + e.FirstName + " " + e.LastName + ">"
}

type Payroll struct {
 Company   Company
 Boss      *Employee
 Employee  *Employee
 StartDate time.Time
 EndDate   time.Time
 Amount    int
}

// Creates a blank payroll for a specific employee with specific boss in specific company
type PayFactory func(Company, *Employee, *Employee) Payroll

// Creates a blank payroll for a specific employee
type CustomPayFactory func(*Employee) Payroll

func CurryPayFactory(pf PayFactory, company Company, boss *Employee) CustomPayFactory {
 return func(e *Employee) Payroll {
  return pf(company, boss, e)
 }
}

func NewPay(company Company, boss *Employee, employee *Employee) Payroll {
 return Payroll{
  Company:  company,
  Boss:     boss,
  Employee: employee,
 }
}

func main() {
 me := Employee{"Jack""Power"}

 // I happen to be head of the HR department of Richissim Inc.
 var myLittlePayFactory CustomPayFactory = CurryPayFactory(NewPay, "Richissim", &me)

 fmt.Println(myLittlePayFactory(&Employee{"Jean""Dupont"}))
 fmt.Println(myLittlePayFactory(&Employee{"Antoine""Pol"}))
}

{Richissim <Jack Power> <Jean Dupont> 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0}
{Richissim <Jack Power> <Antoine Pol> 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC 0}

fn add(a: u32, b: u32) -> u32 {
    a + b
}

fn main() {
    let add5 = move |x| add(5, x);

    let y = add5(12);
    println!("{}", y);
}

输出

17


38. Extract a substring

Find substring t consisting in characters i (included) to j (excluded) of string s. Character indices start at 0 unless specified otherwise. Make sure that multibyte characters are properly handled.

查找由字符串s的字符I(包括)到j(不包括)组成的子字符串t。 除非另有说明,字符索引从0开始。 确保正确处理多字节字符。

package main

import "fmt"

func main() {
 s := "hello, utf-8 문자들"
 i, j := 715
 
 t := string([]rune(s)[i:j])
 
 fmt.Println(t)
}

utf-8 문자


extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;

fn main() {
    let s = "Lorem Ipsüm Dolor";
    let (i, j) = (611);
    let t = s.graphemes(true).skip(i).take(j - i).collect::<String>();
    println!("{}", t);
}

输出

Ipsüm

or

use substring::Substring;
let t = s.substring(i, j);


39. Check if string contains a word

Set boolean ok to true if string word is contained in string s as a substring, or to false otherwise.

如果字符串单词作为子字符串包含在字符串s中,则将布尔ok设置为true,否则设置为false。

package main

import (
 "fmt"
 "strings"
)

func main() {
 s := "Let's dance the macarena"

 word := "dance"
 ok := strings.Contains(s, word)
 fmt.Println(ok)

 word = "car"
 ok = strings.Contains(s, word)
 fmt.Println(ok)

 word = "duck"
 ok = strings.Contains(s, word)
 fmt.Println(ok)
}
true
true
false

fn main() {
    let s = "Let's dance the macarena";

    let word = "dance";
    let ok = s.contains(word);
    println!("{}", ok);

    let word = "car";
    let ok = s.contains(word);
    println!("{}", ok);

    let word = "duck";
    let ok = s.contains(word);
    println!("{}", ok);
}

输出

true
true
false

本文由 mdnice 多平台发布

相关文章:

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

21. Swap values 交换变量a和b的值 a, b b, a package mainimport "fmt"func main() { a : 3 b : 10 a, b b, a fmt.Println(a) fmt.Println(b)} 103 fn main() { let a 3; let b 10; let (a, b) (b, a); println!("a: {a}, b: {b}", aa,…...

对于Vue3的一些思考

看完 Vue Hooks: 让Vue开发更简单与高效 - 掘金 一些小心得 vue3&#xff1a; 组合式API&#xff08;是利用架构&#xff0c;强制达到拆分目的&#xff09; 达到解耦的目的。对于vue3来说 每个模块的每个逻辑都是 一个一个独立的方法。通过 方法方法整体业务 代码风格&#…...

Bean的生命周期 - spring

前言 本篇介绍了Bean的生命周期&#xff0c;认识PostConstruct注释&#xff0c;PreDestroy注释&#xff0c;如有错误&#xff0c;请在评论区指正&#xff0c;让我们一起交流&#xff0c;共同进步&#xff01; 文章目录 前言1. spring生命周期2. Bean的生命周期3. 为什么先设置…...

入门Linux基本指令(2)

这篇文章主要提供一些对文件操作的Linux基本指令&#xff0c;希望对大家有所帮助&#xff0c;三连支持&#xff01; 目录 cp指令(复制) mv指令(剪切) nano指令 cat指令(打印文件内容) > 输出重定向 >> 追加重定向 < 输入重定向 more指令 less指令(推荐) …...

【C++】【自用】选择题 刷题总结

文章目录 【类和对象】1. 构造、拷贝构造的调用2. 静态成员变量3. 初始化列表4. 成员函数&#xff1a;运算符重载5. 友元函数、友元类55. 特殊类设计 【细节题】1. 构造 析构 new \ deletet、new[] \ delete[] 【类和对象】 1. 构造、拷贝构造的调用 #include using namespace…...

SkyWalking链路追踪-Collector(收集器)

Collector&#xff08;收集器&#xff09; SkyWalking的Collector&#xff08;收集器&#xff09;是SkyWalking链路追踪的核心组件之一。它负责接收来自各个Agent的追踪数据&#xff0c;并将其存储到数据存储器&#xff08;如数据库&#xff09;中。具体来说&#xff0c;Colle…...

typescript自动编译文件实时更新

npm install -g typescripttsc --init 生成tsconfig.json配置文件 tsc -w 在监听模式下运行&#xff0c;当文件发生改变的时候自动编译...

qt6.5 download for kali/ubuntu ,windows (以及配置选项选择)

download and sign in qt官网 sign in onlion Install 1 2 3 4 5...

【JS 原型链】

JavaScript 原型链是一个重要的概念&#xff0c;它是 JavaScript 语言实现面向对象编程的核心。在 JavaScript 中&#xff0c;每个对象都有一个与之关联的原型&#xff0c;并且该对象继承了原型中的属性和方法。这些原型组成了一个原型链&#xff0c;可以通过该链追溯到顶层的 …...

harmonyOS 开发之UI开发(ArkTS声明式开发范式)概述

UI开发&#xff08;ArkTS声明式开发范式&#xff09;概述 基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、支持跨设备的UI开发框架&#xff0c;提供了构建OpenHarmony应用UI所必需的能力&#xff0c;主要包括&#xff1a; ArkTS ArkTS是UI开发语言&#xff…...

【人工智能】神经网络、M-P_神经元模型、激活函数、神经网络结构、学习网络参数、代价定义、总代价

M-P_神经元模型、激活函数、神经网络结构、学习网络参数、代价定义 文章目录 M-P_神经元模型、激活函数、神经网络结构、学习网络参数、代价定义M-P 神经元模型激活函数(Activation function)神经网络结构举例训练神经网络学习网络参数代价定义均方误差交叉熵(Cross Entropy)…...

小程序新渲染引擎 Skyline 发布正式版

为了进一步提升小程序的渲染性能和体验&#xff0c;我们推出了一套新渲染引擎 Skyline&#xff0c;现在&#xff0c;跟随着基础库 3.0.0 发布 Skyline 正式版。 我们知道&#xff0c;小程序一直用 WebView 来渲染界面&#xff0c;因其有不错的兼容性和丰富的特性&#xff0c;且…...

网络安全作业1

URL编码 当 URL 路径或者查询参数中&#xff0c;带有中文或者特殊字符的时候&#xff0c;就需要对 URL 进行编码&#xff08;采用十六进制编码格式&#xff09;。URL 编码的原则是使用安全字符去表示那些不安全的字符。 安全字符&#xff0c;指的是没有特殊用途或者特殊意义的…...

【NLP】视觉变压器与卷积神经网络

一、说明 本篇是 变压器因其计算效率和可扩展性而成为NLP的首选模型。在计算机视觉中&#xff0c;卷积神经网络&#xff08;CNN&#xff09;架构仍然占主导地位&#xff0c;但一些研究人员已经尝试将CNN与自我注意相结合。作者尝试将标准变压器直接应用于图像&#xff0c;发现在…...

【redis】通过配置文件简述redis的rdb和aof

redis的持久化方式有2种&#xff0c;rdb&#xff0c;即通过快照的方式将全量数据以二进制记录在磁盘中&#xff0c;aof&#xff0c;仅追加文件&#xff0c;将增量的写命令追加在aof文件中。在恢复的时候&#xff0c;rdb要更快&#xff0c;但是会丢失一部分数据。aof丢失数据极少…...

Cypress 上传 pdf 变空白页问题

在使用cypress 上传文件时&#xff0c;上传正常&#xff0c;但是&#xff0c;pdf一直空白的&#xff0c;翻边了资料也没找到原因。最后在一个不起眼的地方发现了问题所在。 错误的代码&#xff1a; cy.fixture(CBKS.pdf).as(uploadFile)cy.get(.el-upload-dragger).selectFile…...

【ArcGIS Pro二次开发】(52):布局导出图片(批量)

在ArcGIS Pro中设定好布局后&#xff0c;可以直接导出为各种类型的图片。 这是很基本的功能&#xff0c;但是如果你的布局很多&#xff0c;一张一张导图就有点费劲。 之前有网友提出希望可以批量导图&#xff0c;要实现起来并不难&#xff0c;于是就做了这个工具。 一、要实现…...

Git拉取远程分支并创建本地分支

一、查看远程分支 使用如下git命令查看所有远程分支&#xff1a; git branch -r 查看远程和本地所有分支&#xff1a; git branch -a 查看本地分支&#xff1a; git branch 在输出结果中&#xff0c;前面带* 的是当前分支。 二、拉取远程分支并创建本地分支 方法一 使用…...

OSI七层模型——物理层

OSI模型的物理层位于协议栈的底部。它是 TCP/IP 模型的网络接入层的一部分。如果没有物理层&#xff0c;就没有网络。本模块详细介绍了连接到物理层的三种方法。 1 物理层的用途 1.1 物理连接 不管是在家连接本地打印机还是将其连接到另一国家/地区的网站上&#xff0c;在进…...

【NLP】使用变压器(tranformer)和自动编码器

一、说明 自然语言处理 (NLP)中,trnsformer和编码器是至关重要的概念;本篇不是探讨原理,而是讲现实中,如何调用和使用transformer以及encoder,注意。本文中有时出现“变压器”,那是transormer的同义词,在此事先声明。 二、NLP及其重要性的简要概述 NLP是人工…...

IGP(Interior Gateway Protocol,内部网关协议)

IGP&#xff08;Interior Gateway Protocol&#xff0c;内部网关协议&#xff09; 是一种用于在一个自治系统&#xff08;AS&#xff09;内部传递路由信息的路由协议&#xff0c;主要用于在一个组织或机构的内部网络中决定数据包的最佳路径。与用于自治系统之间通信的 EGP&…...

【第二十一章 SDIO接口(SDIO)】

第二十一章 SDIO接口 目录 第二十一章 SDIO接口(SDIO) 1 SDIO 主要功能 2 SDIO 总线拓扑 3 SDIO 功能描述 3.1 SDIO 适配器 3.2 SDIOAHB 接口 4 卡功能描述 4.1 卡识别模式 4.2 卡复位 4.3 操作电压范围确认 4.4 卡识别过程 4.5 写数据块 4.6 读数据块 4.7 数据流…...

SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现

摘要 本论文旨在设计并实现基于 SpringBoot 和 uniapp 的 Champion 俱乐部微信小程序&#xff0c;以满足俱乐部线上活动推广、会员管理、社交互动等需求。通过 SpringBoot 搭建后端服务&#xff0c;提供稳定高效的数据处理与业务逻辑支持&#xff1b;利用 uniapp 实现跨平台前…...

三体问题详解

从物理学角度&#xff0c;三体问题之所以不稳定&#xff0c;是因为三个天体在万有引力作用下相互作用&#xff0c;形成一个非线性耦合系统。我们可以从牛顿经典力学出发&#xff0c;列出具体的运动方程&#xff0c;并说明为何这个系统本质上是混沌的&#xff0c;无法得到一般解…...

【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具

第2章 虚拟机性能监控&#xff0c;故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令&#xff1a;jps [options] [hostid] 功能&#xff1a;本地虚拟机进程显示进程ID&#xff08;与ps相同&#xff09;&#xff0c;可同时显示主类&#x…...

Java线上CPU飙高问题排查全指南

一、引言 在Java应用的线上运行环境中&#xff0c;CPU飙高是一个常见且棘手的性能问题。当系统出现CPU飙高时&#xff0c;通常会导致应用响应缓慢&#xff0c;甚至服务不可用&#xff0c;严重影响用户体验和业务运行。因此&#xff0c;掌握一套科学有效的CPU飙高问题排查方法&…...

【电力电子】基于STM32F103C8T6单片机双极性SPWM逆变(硬件篇)

本项目是基于 STM32F103C8T6 微控制器的 SPWM(正弦脉宽调制)电源模块,能够生成可调频率和幅值的正弦波交流电源输出。该项目适用于逆变器、UPS电源、变频器等应用场景。 供电电源 输入电压采集 上图为本设计的电源电路,图中 D1 为二极管, 其目的是防止正负极电源反接, …...

C#学习第29天:表达式树(Expression Trees)

目录 什么是表达式树&#xff1f; 核心概念 1.表达式树的构建 2. 表达式树与Lambda表达式 3.解析和访问表达式树 4.动态条件查询 表达式树的优势 1.动态构建查询 2.LINQ 提供程序支持&#xff1a; 3.性能优化 4.元数据处理 5.代码转换和重写 适用场景 代码复杂性…...

通过MicroSip配置自己的freeswitch服务器进行调试记录

之前用docker安装的freeswitch的&#xff0c;启动是正常的&#xff0c; 但用下面的Microsip连接不上 主要原因有可能一下几个 1、通过下面命令可以看 [rootlocalhost default]# docker exec -it freeswitch fs_cli -x "sofia status profile internal"Name …...

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

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