Rust: join,与concat
Rust的高阶函数使用频率很高,经常会碰到“扁平化”的降维处理,此时,join与concat的作用很明显。经常可能用到。
一、看官方标准库的文档用法说明
concat:
fn concat(&self) -> Self::Output Flattens a slice of T into a single value Self::Output. Examples assert_eq!(["hello", "world"].concat(), "helloworld"); assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
join:
fn join(&self, sep: &T) -> Self::Output Flattens a slice of T into a single value Self::Output, placing a given separator between each. Examples assert_eq!(["hello", "world"].join(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
二、说明
1、区别是,join()是必需带参数的,而concat是不能带参的光杆司令。
2、其作用有时很明显不一样。
join、concat有些时侯的作用是互补的,完全不能替代。比如,join就无法达到concat的效果。
assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]); assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
3、&str,String
let data = ["hello", "world"].concat(); let data2 = ["hello".to_string(), "world".to_string()].concat(); //let names: Vec<&str> = contacts.keys().iter().map(|&x| x).collect(); let data3 = ["hello", "world"].join("+"); let data4 = ["hello".to_string(), "world".to_string()].join("");
4、Vec,[]: Vec也是可以的。
let data = vec!["hello", "world"].concat(); let data2 = vec!["hello".to_string(), "world".to_string()].concat(); //let names: Vec<&str> = contacts.keys().iter().map(|&x| x).collect(); let data3 = vec!["hello", "world"].join("+"); let data4 = vec!["hello".to_string(), "world".to_string()].join("");
相关推荐
zhangxiafll 2020-11-13
svap 2020-11-09
viplinux 2020-10-28
Justhavefun 2020-10-22
lousir 2020-10-21
longzhiwen 2020-10-16
Justhavefun 2020-09-25
归去来兮 2020-09-18
zhouxiaojie 2020-09-16
gamedevd 2020-09-04
tkernel 2020-09-03
Trustport 2020-09-01
svap 2020-08-25
tkernel 2020-08-18
lihn 2020-08-18
归去来兮 2020-07-28
TianlangStudio 2020-07-18
iammjun 2020-07-07
Colourful 2020-07-03