国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Rust vs Go:常用語法對比(二)

這篇具有很好參考價值的文章主要介紹了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:?",?a=a,?b=b);
}

輸出

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);
}

輸出

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
type:?string
123
type:?int

or

import?"strconv"
i,?err?:=?strconv.ParseInt(s,?10,?0)
package?main

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

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

?i,?err?:=?strconv.ParseInt(s,?10,?0)
?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=1`?for?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.

創(chuàng)建一個二維數組

聲明并初始化一個有m行n列的矩陣x,包含實數。

const?m,?n?=?3,?4
var?x?[m][n]float64
package?main

import?"fmt"

func?main()?{
?const?m,?n?=?3,?4
?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(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
}

[[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.

創(chuàng)建一個三維數組

聲明并初始化一個三維數組x,它有m,n,p維邊界,并且包含實數。

const?m,?n,?p?=?2,?2,?3
var?x?[m][n][p]float64
package?main

import?"fmt"

func?main()?{
?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)
}
[[[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(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
}
[[[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![1,?2,?3];
????assert_eq!(v.remove(1),?2);
????assert_eq!(v,?[1,?3]);
????
}

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ā)執(zhí)行。 任務是獨立的,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)

創(chuàng)建遞歸函數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.

創(chuàng)建函數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(3,?5))
}

輸出

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)?B,?g?func(B)?C)?func(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),?10,?32)
?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?*?2)?as?i32;
????let?g?=?|x:?i32|?(x?+?1)?as?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)?int,?g?func(int)?int)?func(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?*?2)?as?i32;
????let?g?=?|x:?i32|?(x?+?1)?as?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開始。 確保正確處理多字節(jié)字符。

package?main

import?"fmt"

func?main()?{
?s?:=?"hello,?utf-8????"
?i,?j?:=?7,?15
?
?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)?=?(6,?11);
????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 多平臺發(fā)布文章來源地址http://www.zghlxwxcb.cn/news/detail-602934.html

到了這里,關于Rust vs Go:常用語法對比(二)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯(lián)網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • Rust vs Go:常用語法對比(七)

    Rust vs Go:常用語法對比(七)

    題圖來自 Go vs Rust: Which will be the top pick in programming? [1] 121. UDP listen and read Listen UDP traffic on port p and read 1024 bytes into buffer b. 聽端口p上的UDP流量,并將1024字節(jié)讀入緩沖區(qū)b。 122. Declare enumeration Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS. 聲明枚舉值 Hearts

    2024年02月15日
    瀏覽(20)
  • Rust vs Go:常用語法對比(十)

    Rust vs Go:常用語法對比(十)

    題圖來自 Rust vs. Golang: Which One is Better? [1] 182. Quine program Output the source of the program. 輸出程序的源代碼 輸出: 另一種寫法: //go:embed 入門 [2] Quine 是一種可以輸出自身源碼的程序。利用 go:embed 我們可以輕松實現 quine 程序: 輸出: or 輸出: fn main(){print!(\\\"{},{0:?})}}\\\",\\\"fn main(){pri

    2024年02月15日
    瀏覽(23)
  • Rust vs Go:常用語法對比(十一)

    Rust vs Go:常用語法對比(十一)

    題目來自 Rust Vs Go: Which Language Is Better For Developing High-Performance Applications? [1] 202. Sum of squares Calculate the sum of squares s of data, an array of floating point values. 計算平方和 +1.094200e+000 32.25 205. Get an environment variable Read an environment variable with the name \\\"FOO\\\" and assign it to the string variable foo. If i

    2024年02月15日
    瀏覽(19)
  • Rust vs Go:常用語法對比(十二)

    Rust vs Go:常用語法對比(十二)

    題圖來自 Rust vs Go in 2023 [1] 221. Remove all non-digits characters Create string t from string s, keeping only digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 刪除所有非數字字符 168 [src/main.rs:7] t = \\\"14\\\" 222. Find first index of an element in list Set i to the first index in list items at which the element x can be found, or -1 if items doe

    2024年02月15日
    瀏覽(16)
  • Rust vs Go:常用語法對比(五)

    Rust vs Go:常用語法對比(五)

    題圖來自 Rust vs Go 2023 [1] 81. Round floating point number to integer Declare integer y and initialize it with the rounded value of floating point number x . Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity). 按規(guī)則取整 2.71828 3 82. Count substring occurrences 統(tǒng)計子字符串出現次數 1 Disjoint ma

    2024年02月15日
    瀏覽(24)
  • Rust vs Go:常用語法對比(三)

    Rust vs Go:常用語法對比(三)

    題圖來自 When to use Rust and when to use Go [1] 41. Reverse a string 反轉字符串 輸出 or 輸出 ? roma tis r?lod müspi mérol 42. Continue outer loop Print each item v of list a which in not contained in list b. For this, write an outer loop to iterate on a and an inner loop to iterate on b. 打印列表a中不包含在列表b中的每個項目

    2024年02月16日
    瀏覽(23)
  • Rust vs Go:常用語法對比(六)

    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. 發(fā)起http請求 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 or or 102. Load from H

    2024年02月15日
    瀏覽(25)
  • Java VS Go 還在糾結怎么選嗎,(資深后端4000字帶你深度對比)

    Java VS Go 還在糾結怎么選嗎,(資深后端4000字帶你深度對比)

    今天我們來聊一下Go 和Java,本篇文章主要是想給對后臺開發(fā)的初學者和有意向選擇Go語言的有經驗的程序員一些建議,希望能幫助各位自上而下的來了解一下Java和Go的全貌。 作為一個多年的Java后端開發(fā),用的時間久了就會發(fā)現Java語言一些問題,所謂婚前風花雪月,婚后柴米

    2024年02月04日
    瀏覽(26)
  • 【字節(jié)跳動青訓營】后端筆記整理-1 | Go語言入門指南:基礎語法和常用特性解析

    【字節(jié)跳動青訓營】后端筆記整理-1 | Go語言入門指南:基礎語法和常用特性解析

    **本人是第六屆字節(jié)跳動青訓營(后端組)的成員。本文由博主本人整理自該營的日常學習實踐,首發(fā)于稀土掘金:??Go語言入門指南:基礎語法和常用特性解析 | 青訓營 本文主要梳理自 第六屆字節(jié)跳動青訓營(后端組)-Go語言原理與實踐第一節(jié)(王克純老師主講) 。同時

    2024年02月13日
    瀏覽(24)
  • 【Rust日報】2023-02-14 Rust GUI 框架對比: Tauri vs Iced vs egui

    【Rust日報】2023-02-14 Rust GUI 框架對比: Tauri vs Iced vs egui

    Rust GUI 框架對比: Tauri vs Iced vs egui Tauri:使用系統(tǒng)的 webview 來渲染 HTML/JS 的前端。你可以選擇任何前端框架。后臺是用Rust編寫的,可以通過內置的方法與前臺通信。 Iced: 受 Elm 啟發(fā)的(響應式)GUI庫。在桌面上使用 wgpu 進行渲染;實驗性的web后端創(chuàng)建DOM進行渲染。所有代碼

    2024年02月02日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包