21. Swap values
Swap the values of variables A and B
a, b = b, a
Copy the code
package main
import "fmt"
func main(a) {
a := 3
b := 10
a, b = b, a
fmt.Println(a)
fmt.Println(b)
}
Copy the code
10
3
Copy the code
fn main() {
let a = 3;
let b = 10;
let (a, b) = (b, a);
println!("a: {a}, b: {b}", a=a, b=b);
}
Copy the code
The output
a: 10, b: 3
or
fn main() {
let (a, b) = (12.42);
println!("a = {}, b = {}", a, b);
let (a, b) = (b, a);
println!("a = {}, b = {}", a, b);
}
Copy the code
The output
a = 12, b = 42
a = 42, b = 12
Copy the code
22. Convert string to integer
Converts a string to an integer
import "strconv"
i, err := strconv.Atoi(s)
Copy the code
package main
import (
"fmt"
"reflect"
"strconv"
)
func main(a) {
// create a string
s := "123"
fmt.Println(s)
fmt.Println("type:", reflect.TypeOf(s))
// convert string to int
i, err := strconv.Atoi(s)
iferr ! =nil {
panic(err)
}
fmt.Println(i)
fmt.Println("type:", reflect.TypeOf(i))
}
Copy the code
123
type: string
123
type: int
Copy the code
or
import "strconv"
i, err := strconv.ParseInt(s, 10.0)
Copy the code
package main
import (
"fmt"
"reflect"
"strconv"
)
func main(a) {
s := "123"
fmt.Println("s is", reflect.TypeOf(s), s)
i, err := strconv.ParseInt(s, 10.0)
iferr ! =nil {
panic(err)
}
fmt.Println("i is", reflect.TypeOf(i), i)
}
Copy the code
s is string 123
i is int64 123
Copy the code
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);
}
Copy the code
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);
}
Copy the code
The output
123
0
Copy the code
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);
}
Copy the code
The output
123
-1
Copy the code
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.
Given a real number, keep two decimal places after the decimal point
package main
import "fmt"
func main(a) {
x := 3.14159
s := fmt.Sprintf("%.2f", x)
fmt.Println(s)
}
Copy the code
The output
3.14
fn main() {
let x = 42.1337;
let s = format!(. ": {2}", x);
println!("{}", s);
}
Copy the code
The output
42.13
24. Assign to string the Japanese word ネ (I’m back)
Declare a new string s and initialize it with the literal value “ネ (which means “cat” in Japanese)
Declare a new string, S, and initialize it with the literal value “ネ (called)” (which means “cat” in Japanese).
package main
import "fmt"
func main(a) {
s := "ネ コ"
fmt.Println(s)
}
Copy the code
fn main() {
let s = "ネ コ";
println!("{}", s);
}
Copy the code
25. Send a value to another thread
Share the string value “Alan” with an existing running process which will then display “Hello, Alan”
Share the string value “Alan” with an existing running process that displays “Hello Alan”
ch <- "Alan"
Copy the code
package main
import (
"fmt"
"time"
)
func main(a) {
ch := make(chan string)
go func(a) {
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)
}
Copy the code
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();
}
Copy the code
Hello, output “Alan”
26. Create a 2-dimensional array
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
Create a two-dimensional array
Declares and initializes a matrix x with m rows and n columns, containing real numbers.
const m, n = 3.4
var x [m][n]float64
Copy the code
package main
import "fmt"
func main(a) {
const m, n = 3.4
var x [m][n]float64
x[1] [2] = 8
fmt.Println(x)
}
Copy the code
[[0 0 0 0] [0 0 8 0] [0 0 0 0]]
or
package main
import "fmt"
func main(a) {
x := make2D(2.3)
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
}
Copy the code
[[0 0 0]]
fn main() {
const M: usize = 4;
const N: usize = 6;
let x = vec![vec![0.0 f64; N]; M];
println!("{: #? }", x);
}
Copy the code
The output
[[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,]]Copy the code
fn main() {
const M: usize = 3;
const N: usize = 4;
let mut x = [[0.0; N] ; M];
x[1] [3] = 5.0;
println!("{: #? }", x);
}
Copy the code
The output
[[0.0.0.0.0.0.0.0,], [0.0.0.0.0.0.5.0,], [0.0.0.0.0.0.0.0,]]Copy the code
27. Create a 3-dimensional array
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
Create a three-dimensional array
Declares and initializes a three-dimensional array x that has m, n, and p-dimensional boundaries and contains real numbers.
go
const m, n, p = 2.2.3
var x [m][n][p]float64
Copy the code
package main
import "fmt"
func main(a) {
const m, n, p = 2.2.3
var x [m][n][p]float64
x[1] [0] [2] = 9
// Value of x
fmt.Println(x)
// Type of x
fmt.Printf("%T", x)
}
Copy the code
[[[0 0 0] [0 0 0]] [[0 0 9] [0 0 0[]]]2] [2] [3]float64
Copy the code
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
}
Copy the code
package main
import "fmt"
func main(a) {
x := make3D(2.2.3)
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
}
Copy the code
[[[0 0 0] [0 0 0]] [[0 0 9] [0 0 0]]]
Copy the code
fn main() {
let m = 4;
let n = 6;
let p = 2;
let x = vec![vec![vec![0.0 f64; p]; n]; m];
println!("{: #? }", x);
}
Copy the code
The output
[[[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,]]]Copy the code
fn main() {
const M: usize = 4;
const N: usize = 6;
const P: usize = 2;
let x = [[[0.0 f64; P]; N]; M];
println!("{: #? }", x);
}
Copy the code
The output
[[[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,]]]Copy the code
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.
Sort the elements of an array-like collection item in ascending order x->p, where P is the field of the item type of the object in the item.
go
package main
import "fmt"
import "sort"
type Item struct {
label string
p int
lang string
}
type ItemPSorter []Item
func (s ItemPSorter) Len(a) 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(a) {
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)
}
Copy the code
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}]
Copy the code
or
package main
import "fmt"
import "sort"
type Item struct {
label string
p int
lang string
}
func main(a) {
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)
}
Copy the code
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}]
Copy the code
#[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);
}
Copy the code
The output
[Foo { p: 1 }, Foo { p: 2 }, Foo { p: 3 }, Foo { p: 4 }]
Copy the code
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);
}
Copy the code
The output
[Foo { p: 1 }, Foo { p: 2 }, Foo { p: 3 }, Foo { p: 4 }]
Copy the code
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.
Removes item I from the list item. This will change the original list or return a new list, depending on which is more customary. Note that in most languages, the minimum valid value for I is 0.
package main
import (
"fmt"
)
func main(a) {
items := []string{"a"."b"."c"."d"."e"."f"}
fmt.Println(items)
i := 2
items = append(items[:i], items[i+1:]...). fmt.Println(items) }Copy the code
[a b c d e f]
[a b d e f]
Copy the code
or
copy(items[i:], items[i+1:])
items[len(items)- 1] = nil
items = items[:len(items)- 1]
Copy the code
fn main() {
let mut v = vec![1.2.3];
assert_eq!(v.remove(1), 2);
assert_eq!(v, [1.3]);
}
Copy the code
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.
Start concurrent execution of program F with argument I from 1 to 1000. The task is independent and f(I) does not return a value. Tasks do not need to run at the same time, so pools can be used
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()
Copy the code
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(a) {
for i := 1; i <= 1000; i++ {
go f(i)
}
time.Sleep(4 * time.Second)
}
Copy the code
use std::thread;
fn main() {
let threads: VecThe < _ > = (0.1000).map(|i| thread::spawn(move || f(i))).collect();
for thread inthreads { thread.join(); }}fn f(i: i32) {
println!("{}", i);
}
Copy the code
or
extern crate rayon;
use rayon::prelude::*;
fn main() {(0.1000).into_par_iter().for_each(f);
}
fn f(i: i32) {
println!("{}", i);
}
Copy the code
31. Recursive factorial (simple)
Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)
Creates a recursive function f that returns the factorial of the non-negative integer I evaluated from f(i-1)
func f(i int) int {
if i == 0 {
return 1
}
return i * f(i- 1)}Copy the code
package main
import (
"fmt"
)
func f(i int) int {
if i == 0 {
return 1
}
return i * f(i- 1)}func main(a) {
for i := 0; i <= 10; i++ {
fmt.Printf("f(%d) = %d\n", i, f(i))
}
}
Copy the code
The output
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
Copy the code
fn f(n: u32) - >u32 {
if n < 2 {
1
} else {
n * f(n - 1)}}fn main() {
println!("{}", f(4 as u32));
}
Copy the code
The output
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));
}
Copy the code
The output
1
1
2
6
24
120
Copy the code
32. Integer exponentiation by squaring
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
Create the function exp to compute the value of n to the (quick)x power. X and n are non-negative integers.
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(a) {
fmt.Println(exp(3.5))}Copy the code
The output
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));
}
Copy the code
The output
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.
Assign a new value f(x) to variable x, ensuring that no other thread can modify x between reads and writes.
package main
import (
"fmt"
"sync"
)
func main(a) {
var lock sync.RWMutex
x := 3
lock.Lock()
x = f(x)
lock.Unlock()
fmt.Println(x)
}
func f(i int) int {
return 2 * i
}
Copy the code
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);
}
Copy the code
The output
1
34. Create a set of objects
Declare and initialize a set x containing objects of type T.
Declares and initializes a collection x containing objects of type T.
go
x := make(map[T]bool)
Copy the code
package main
import "fmt"
type T string
func main(a) {
// 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)
}
}
Copy the code
x contains element D
x contains element A
x contains element B
Copy the code
or
x := make(map[T]struct{})
Copy the code
package main
import "fmt"
type T string
func main(a) {
// 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)
}
}
Copy the code
x contains element B
x contains element D
x contains element A
Copy the code
use std::collections::HashSet;
fn main() {
let mut m = HashSet::new();
m.insert("a");
m.insert("b");
println!("{:? }", m);
}
Copy the code
The output
{"a"."b"}
Copy the code
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
CVD: Compose (A -> C) implement A function compose (A -> C) with parameters F (A -> B) and G (B -> C), and return composition function G ∘ F
package main
import "fmt"
import "strconv"
func compose(f func(A) B.g func(B) C) func(A) C {
return func(x A) C {
return g(f(x))
}
}
func main(a) {
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), 10.32)
return B(b)
}
func square(b B) C {
return C(b * b)
}
Copy the code
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)))
}
Copy the code
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 * 2) as i32;
let g = |x: i32| (x + 1) as f32;
let c = compose(f, g);
println!("{}", c(2));
}
Copy the code
The output
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.
CVD implements a function composition that returns the CVD function G ∘ F for any function F and G that has exactly 1 argument.
package main
import "fmt"
func composeIntFuncs(f func(int) int.g func(int) int) func(int) int {
return func(x int) int {
return g(f(x))
}
}
func main(a) {
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)))
}
}
Copy the code
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
Copy the code
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)))
}
Copy the code
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 * 2) as i32;
let g = |x: i32| (x + 1) as f32;
let c = compose(f, g);
println!("{}", c(2));
}
Copy the code
The output
5
37. Currying
Transform a function that takes multiple arguments into a function for which some of the arguments are preset.
Converts a function that takes multiple arguments to a function that presuppositions certain arguments.
package main
import (
"fmt"
"time"
)
type Company string
type Employee struct {
FirstName string
LastName string
}
func (e *Employee) String(a) 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(a) {
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"}}))Copy the code
{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}
Copy the code
fn add(a: u32, b: u32) - >u32 {
a + b
}
fn main() {
let add5 = move |x| add(5, x);
let y = add5(12);
println!("{}", y);
}
Copy the code
The output
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.
Find the substring t consisting of characters I(inclusive) through j(exclusive) of the string s. Character indexes start at 0 unless otherwise noted. Make sure multibyte characters are handled correctly.
package main
import "fmt"
func main(a) {
s := "hello, utf-8 문자들"
i, j := 7.15
t := string([]rune(s)[i:j])
fmt.Println(t)
}
Copy the code
Utf-8 문 자
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let s = "Lorem Ipsum Dolor." ";
let (i, j) = (6.11);
let t = s.graphemes(true).skip(i).take(j - i).collect::<String> ();println!("{}", t);
}
Copy the code
The output
Ipsüm
or
use substring::Substring;
let t = s.substring(i, j);
Copy the code
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.
Set Boolean OK to true if the string word is contained as a substring in string S, false otherwise.
package main
import (
"fmt"
"strings"
)
func main(a) {
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)
}
Copy the code
true
true
false
Copy the code
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);
}
Copy the code
The output
true
true
false
Copy the code