← 返回技术雷达
Hacker News tech

Stabilizing Rust's Never Type

Hacker News 热议:Stabilizing Rust's Never Type(88 赞 / 10 评论,来源 lwn.net)

一句话概要

A function’s return type is supposed to indicate the kind of data that it produces. Rust’s ‘n […]

原文开头节选

(Note: Rust also uses exclamation marks to indicate calls to macros. The way the syntax is constructed, a place where it is valid to use the never type is not a valid place to put a macro invocation and vice versa.)

There are two reasons that Rust has a never type, one practical and one philosophical. The practical reason is that it allows for more efficient generic code. For example, consider the FromStr trait in the standard library, which is used for types that can be instantiated from a string:

trait FromStr: Sized { type Err; fn from_str(s: &str) -> Result<Self, Self::Err>; } FromStr::from_str() either returns a converted result, or a custom error type. For example, attempting to convert “foo” into an integer will return a ParseIntError . But some types have an infallible conversion. For example, it is always possible to convert a string into a ByteString . That implementation of FromStr could set Err to be the never type.

impl FromStr for ByteString { type Err = !; fn from_str(s: &str) -> Result<Self, !> { …

(以上为原文节选,完整内容见下方”原文来源”)

这条动态今日登上 Hacker News 首页(88 赞 / 10 评论,来源 lwn.net)。技术雷达每日自动聚合 AI 工程、后端架构、DevOps 方向的前沿动态;相关工程落地可浏览下方的相关服务与延伸阅读,或直接与我们团队交流。

原文来源: Hacker News

相关服务