[Rust] parse().unwrap()

This lesson explains Type Inference in Rust and how it allows the compiler to figure out by itself, what type variables have when they get their values assigned.

There are cases when the compiler cannot infer a value's type through static analysis. In such cases, developers have to provide type annotations explicitly.

 

In many cases, Rust can infer the types from the code:

#[allow(warnings)]

fn main() {

  let condition = false;

  let some_number = 5;

  let string_number = "5";

  let names = ["Bob", "Alice", "Cindy"];
}

 

But some cases not:

let string_number = "5";
let number = string_number.parse().unwrap();

This is because parse().unwrap()can be a string or number. So you need to tell the compiler what is the expected output.

let number: String = string_number.parse().unwrap(); // to string
let number: int32 = string_number.parse().unwrap(); // to int32

 

Another way is to use turbofish syntax

let number = string_number.parse::<String>().unwrap();
let number = string_number.parse::<int32>().unwrap();

 

posted @   Zhentiw  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-19 [State Machine] Zag-js
2023-02-19 [React] React hook, component props for refactoring
2020-02-19 【逻辑思维】排中律:生存还是毁灭,只能选一个
2020-02-19 【逻辑思维】矛盾律:谁给理发师理发
2020-02-19 [AST Babel] Create a simple babel plugin
2020-02-19 [Angular 8 Unit testing] Testing a smart component with service injection -- 1
2019-02-19 [React] Ensure all React useEffect Effects Run Synchronously in Tests with react-testing-library
点击右上角即可分享
微信分享提示