use std::fs::read_to_string; use std::error::Error; // 定义错误类型MyCustomError #[derive(Debug)] enum MyCustomError { EnvironmentVariableNotFound, IOError(std::io::Error), } // 自定义错误类型MyCustomError实现Error trait后,才
Compiling playground v0.0.1 (/playground) Finished dev [unoptimized + debuginfo] target(s) in 0.60s Running `target/debug/playground`Standard Outputthe add function value of is : 66 小结 今天以代码为例子,分别讲了Rust中函数的定义,以及高阶函数的使用,最我们还简单的提了提闭包。
error: process didn't exit successfully: `target\debug\error_example.exe` (exit code: 101) 由于unwrap与expect会引发panic导致程序崩溃,所以错误处理中不建议这么去做,更千万别在库中写这两个方法。不过在个人写项目时还是有些用的,比如你可能这里出现错误的概率较小,等到出发了这个错误再进行更为细致的处理...
fn another_function(x: i32, y: f32) { println!("The value of x is: {}", x); println!("The value of y is: {}", y); } 1. 2. 3. 4. 5. 6. 7. 8. 四、函数返回 在 Rust 中函数就是表达式,因此我们可以把函数的返回值直接赋给调用者。 函数的返回值就是函数体...
Running `target/debug/variables` The value of x is: 5 The value of x is: 6 加上mut后,我们就可以将x绑定的值从5改成6。归根结底,决定是否使用可变性取决于您,并取决于您知道自己在做什么。 常数 与不可变变量一样,常量是绑定到变量且不允许更改的值,但常量和变量之间存在一些差异。
Running`target/debug/hello_cargo`func hello main hello 上面是经过改造后的代码,运行都可以打印,但是no_takes_ownership并没有拥有 owner,&str表示对字符串的只读引用。no_takes_ownership(&s), 这里没有直接写s, 而是取引用&s 指针与引用 代码语言:javascript ...
debug(hello, world); // hello silently downgrades from `&'static str` into `&'world str` } } ``` `&'static str`隐式地降级为`&'world str`,因此可以编译。 Q:为什么可以降级? A:因为借用是顺变(covariance)的,已知`'static: 'world`,故`&'static str: &'world str`。
error: process didn't exit successfully: `target\debug\cargo_learn.exe` (exit code: 101) 在这里,我们尝试访问向量的第100个元素(索引从零开始,因此它位于索引99),但是它只有3个元素。 在这种情况下,Rust会panic。应该使用[]返回一个元素,但是如果传递无效索引,则Rust不会在此处返回正确的元素。
function: 一个Option<&'a str>类型的字段,表示函数名。如果不可用,则为None。 这个结构体的一个主要作用是提供给panic宏的panic!(...)宏在出现panic时输出更加详细的错误信息,包括panic的文件名、行号、列号和函数名等等。 此外,Location<'a>结构体还定义了一些辅助方法来获取和打印位置信息,包括: fn file(...
Running`target/debug/fun`Hello, world!hello another_function! 函数的参数# 很多时候, 函数需要根据参数来进行操作, rust需要在建立函数时定义参数的名称与类型, 写在函数名后的()中 fnmain(){another_function(5);}fnanother_function(x:i32){println!("x = {}",x);} ...