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("");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值