How to change the type of Vec<i64> to Vec<u64> without using for loop?

Is there any smarter way to do type conversion on Vec rather than using for loop?

This question is better suited to URLO.

bytemuck::cast_vec is one way.

1 Like

many thanks anyway

Using into_iter + map + collect gets optimized well, too:

pub fn convert(x: Vec<i64>) -> Vec<u64> {
    x.into_iter().map(|n| n as _).collect()
}

Rust Playground (click “ASM” as a build option)

playground::convert:
	movq	%rdi, %rax
	movq	(%rsi), %rcx
	movups	8(%rsi), %xmm0
	movq	%rcx, (%rdi)
	movups	%xmm0, 8(%rdi)
	retq
5 Likes