pointers - If I want to code in Rust securely, should I code without using pointer arithmetic?
问题描述
I've read that pointer arithmetic in Rust can be done through the pointer.offset()
function, but it always has to be implemented in unsafe code
:
fn main() {
let buf: [u32; 5] = [1, 2, 3, 4, 5];
let mut ptr1: *const u32 = buf.as_ptr();
unsafe {
let ptr2: *const u32 = buf.as_ptr().offset(buf.len() as isize);
while ptr1 < ptr2 {
println!("Address {:?} | Value {}", ptr1, *ptr1);
ptr1 = ptr1.offset(1);
}
}
}
If I want to code in Rust securely, should I code without using pointer arithmetic and just using the corresponding index of an array for example? Or is there any other way?
解决方案
If I want to code in Rust securely
Then you should not use unsafe
. There are a few legit reasons for unsafe
(e.g. accessing memory locations that are known and safe to use, e.g. on microcontrollers several registers), but generally you should not use it.
should I code without using pointer arithmetic and just using the corresponding index of an array for example
Yes. There is no reason (in this specific case) to use unsafe
at all. Just use
for i in 0..buf.len() {
println!("Value {}", buf[i]);
}
This code however is not considered as "rusty", instead use a for-loop
for i in &buf {
println!("Value {}", i);
}
推荐阅读
- lotusscript - Lotusscript forall 循环未能设置变量
- c++ - mac上如何使用c++17并行标准库算法?
- data-structures - 面向业务分析师的 Salesforce 表关系
- node.js - 使用 Node.js 后端的 React Native 出错
- ibm-doors - DXL 脚本使用 char c = str[i] 产生语法错误
- c - C - 如何在 realloc() 之后添加到 char 数组的末尾
- r - 重置 R Shiny 中 Shinyalert 的输入
- arrays - 如何重复列表中的元素n次?
- python - 将 docker 容器连接到 RDS 数据库
- google-cloud-platform - 为数组数据类型设置 `exclude_from_indexes`