Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - How do I decide when to mark a function as unsafe?

When is it appropriate to mark a function as unsafe versus just using an unsafe block? I saw this function while reading another answer:

unsafe fn as_u8_slice(xs: &[i32]) -> &[u8] {
    std::slice::from_raw_parts(v.as_ptr() as *const u8, 
                               v.len() * std::mem::size_of::<i32>())
}

I probably would have written the function as:

fn as_u8_slice(xs: &[i32]) -> &[u8] {
    unsafe {
        std::slice::from_raw_parts(v.as_ptr() as *const u8, 
                                   v.len() * std::mem::size_of::<i32>())
    }
}

That is, I feel like calling the function is safe in all cases, but what the function does internally cannot be verified by the compiler. However, I don't have any rules for when it is appropriate to use one or the other.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Mark a function as unsafe iff the function's safety depends on its parameters or on global state. If the function is safe regardless of arguments and global state, don't mark it as unsafe. Whether you consider a function that uses unsafe internally safe is the same as whether you consider a C program safe.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...