黎 飞

黎 飞

1659090840

如何在 Rust 中执行单元测试

测试是软件开发的重要组成部分。测试您的代码可确保您开发的软件按预期工作,并使其不易受到攻击者的攻击。

软件测试是一个非常广泛的话题。这就是为什么在软件行业中,有专门从事 QA 和测试的独立专业人员。这些专业人员通常被称为 QA 工程师。

尽管 QA 是它自己的事情,但这并不意味着开发人员根本不进行测试。

开发人员进行的最常见的测试是单元测试。单元测试是一种测试类型,您可以在其中测试小代码单元(如函数)——因此称为单元测试。您通常通过将代码单元的预期行为与其实际行为进行比较来做到这一点。

单元测试是开发工作流程中不可或缺的一部分,以至于一些公司的整个开发文化都围绕着所谓的测试驱动开发(或 TDD)

在 TDD 中,开发人员首先编写测试用例(根据功能需求,通常称为用户故事),然后继续编写满足它们的代码。TDD 主要在要求非常具体的项目中大放异彩。

您可以跨不同的编程语言以不同的方式实施单元测试。但就其核心而言,单元测试只是将代码的预期行为与实际行为进行比较。

因此,无论它是如何以特定语言实现的,当您使用任何其他语言工作时,同样的原则通常适用。

在本教程中,您将学习使用 Rust 编程语言进行单元测试。也就是说,您至少应该了解Rust 编程的基础知识,尽管您不需要高级知识。

所以,说了这么多,让我们继续学习 Rust 的单元测试吧!

单元测试如何在 Rust 中工作

Rust 的核心是代码安全。Rust 严格的类型注释规则有助于在开发阶段的早期消除大量错误。但是,它仍然不是万无一失的。

像任何其他语言一样,业务逻辑在你的肩上,你必须帮助 Rust 理解你的代码中什么是可接受的,什么是不可接受的。

是的,这就是我们进行测试的原因。

您无需安装测试套件即可开始在 Rust 中进行测试,因为它具有内置的测试支持。

首先,--lib在您的本地计算机上创建一个新的货物项目(记下标志)并在您选择的文本编辑器或 IDE 中打开它。对于本教程,我将使用 VS 代码。

cargo new --lib rust_unit_testing
code rust_unit_testing

新建货物库项目

然后,打开src/lib.rs文件。这是我们将在本教程中花费最多时间的地方。

1-2

Rust 库项目的 src/lib.rs 文件

在 Rust 中新创建的库项目中,您会注意到lib.rs默认情况下该文件已由示例测试代码预填充。

这样做的主要目的是让您在编写测试时有一个模板开始。我们将剖析这个简单测试的每个部分,并了解 Rust 中的基本测试概念。

所以首先,让我们了解这些测试代码行在做什么。在此示例中,您将看到一个测试模块,其中定义lib.rs了一个测试,用于测试 2 + 2 是否等于 4。

如果你还不知道 Rust 中模块和属性的概念,那很好,你现在可以忽略它们。

但只是为了让您了解一下,Rust 中的测试是在tests模块内部编写的(mod tests部分说它是测试模块),并且在这个模块中编写的任何内容都告诉 cargo 仅在测试期间运行它们(这本质上是#[cfg(test)]属性所暗示的)。

Rust 中的测试本质上只是一个被注释为测试的函数。从上面的示例中,您会注意到#[test]function 上方的属性it_works。这只是告诉 cargo 这个函数是一个测试,应该在测试期间调用。

it_works测试函数内部,它检查result从 2 + 2 派生的值是否等于 4。它使用assert_eq!宏执行检查。该assert_eq!宏比较==传递给它的左右值的相等性 ( )。

在大多数编程语言中,有一条规则是传递给断言的左边值应该是预期值,而实际值应该在右边。使用 Rust,没有硬性规则,您可以将预期和实际结果传递给任何一方。

现在,尝试使用以下命令运行您的测试:

cargo test

在 cargo 中运行 Rust 测试

以下是上述示例的结果:

2-1

货物测试 - 结果

通过运行cargo test,cargo 将执行您的测试用例并在您的终端中输出报告。从该报告中,您将看到 cargo 运行的测试。

报告的第一行说running 1 test因为我们只有一个测试功能tests::it_works。除了被测试的函数,你会看到消息ok,意思是,测试通过了。

您还可以在下面看到结果摘要:

  • 1 通过
  • 0 失败
  • 0 忽略
  • 0 测量
  • 0 过滤掉
  • 以及结果的状态test result: ok

这里的1 passed计数器代表通过测试的一个测试函数 ( tests::it_works),而failed计数器告诉我们有多少失败的测试。这同样适用于其他计数器。

您还将在下面看到文档测试的结果。由于我们在这里没有任何文档测试,因此您会看到running 0 tests. 您现在可以忽略这一点,只关注单元测试。但是如果你想了解更多,可以查看Rust 的官方文档

如何用 Rust 编写测试

编写测试时,一般需要经过这三个步骤:

  1. 模拟测试用例所需的数据或状态。我的意思是提供您正在测试的代码(如果需要)和/或设置运行测试用例所需的状态或环境所需的模拟或示例数据。
  2. 运行需要测试的代码(传递必要的模拟数据)。一个例子是调用一个你想测试的函数。
  3. 检查您正在测试的代码的实际行为是否与其预期行为相匹配。例如,通过将参数传递x给函数,您可以断言它的返回值是否与您期望它返回的值相同。或者检查一个代码单元是否引发panic!——例如,这是预期的行为——如果给定了某个参数。

在 Rust 中,单元测试被写入被测试代码的确切文件中。然后将测试函数分组在tests模块内(按照惯例以这种方式命名)。

如何在 Rust 中测试函数

现在让我们继续在 Rust 中测试函数。

首先,我们需要一个简单的函数来测试。但首先,删除it_works测试功能,因为我们不再需要它。然后,在模块上面写这个adder函数:tests

// src/lib.rs

pub fn adder(x: i32, y: i32) -> i32 {
    x + y
}

#[cfg(test)]
mod tests {
// ...

加法器函数 - 用于测试的示例代码

上面的adder函数是一个简单的公共函数,它只是将两个数字相加并返回总和。为了测试它是否按预期工作,让我们为此函数编写一个单元测试。

从我们前面讨论的编写单元测试的三个步骤来看,前两个步骤是:

  • 为要测试的代码设置数据
  • 运行代码。

所以回到tests模块,首先,将adder函数带入其范围(使用use关键字)。然后编写一个名为it_adds注解#[test]属性的函数。

// src/lib.rs

pub fn adder (x: i32, y: i32) -> i32 {
    x + y
}

#[cfg(test)]
mod tests {
    // this brings everything from parent's scope into this scope
    use super::*;
    
    #[test]
    fn it_adds() {
    }
}

设置加法器函数的测试

it_addstest 函数内部是我们将编写测试的地方。因此,在其中声明一个名为 的变量sum,然后调用该函数adder并传递 4 和 5 作为其参数(这是我们的模拟数据)。

// src/lib.rs

// --snip--

    #[test]
    fn it_adds() {
        let sum = adder(4, 5);
    }
}

使用模拟数据运行要测试的代码

最后,编写单元测试的第三步是检查我们正在测试的代码的预期行为和实际行为。

所以在这里,让我们使用宏断言函数sum返回的值adder是否等于9(这是我们的预期返回值) 。assert_eq!

// src/lib.rs

// --snip--

    #[test]
    fn it_adds() {
    	let sum = adder(4, 5);
        assert_eq!(sum, 9);
    }
}

断言代码的预期与实际行为

这是文件中代码和测试的最终版本lib.rs

// src/lib.rs

pub fn adder(x: i32, y: i32) -> i32 {
    x + y
}

#[cfg(test)]
mod tests {
    // this brings everything from parent's scope into this scope
    use super::*;

    #[test]
    fn it_adds() {
    	let sum = adder(4, 5);
        assert_eq!(sum, 9);
    }
}

最终版本的代码和测试

如前所述,您可以使用以下命令运行此测试:

cargo test

用货物运行测试用例

如果一切正常,我们应该得到test result: ok说明我们的测试通过了。

3

tests如果您愿意,可以在模块中为函数添加更多测试adder(例如,添加负数)。或者更好的是,创建自己的函数并为它编写一个(或多个测试)测试。

此外,Rust 中还有很多内置的断言宏,您可以在assert_eq!宏之外使用它们。其中一些包括assert_ne!用于断言不相等值!=的宏 ( ),以及assert!仅断言您正在测试的代码是否返回true值的宏。

如果您需要更多的断言宏(例如,支持>, <, >=,的比较断言<=),您可以安装像这样的外部 crate:claim。您可以在此处查看索赔文档以获取更多信息。

为什么失败的测试很有用

到目前为止,我们总是在测试中获得通过结果。

虽然它很好,但单元测试的真正威力来自于在我们的代码中捕捉错误或错误并通过失败的测试报告它们。所以这次,让我们故意写一个“错误”的代码,看看会发生什么。

回到文件中,通过将运算符替换为 来lib.rs修改adder函数。+-

// src/lib.rs

pub fn adder(x: i32, y: i32) -> i32 {
    // change the operator from '+' to '-'
    x - y
}

// --snip--

通过单元测试引入错误以捕获错误

现在再次使用cargo test. 正如预期的那样,您应该会看到一个失败的测试结果,如下所示:

4

货物测试不合格

首先,请注意测试功能的状态tests::it_adds是一个大红色FAILED。这就是货物测试失败的样子。

在此之下,您将看到“失败”报告,其中列出了失败的测试以及有关失败原因的一些信息。

在我们的示例中,tests::it_adds测试失败,正如报告所述,传入宏的左右值assert_eq!不相等 ( ==)。

那是因为左边的值是-1,而右边的值是9。请记住,在我们的assert_eq!断言中,我们传递给它的左值是sum包含返回值的变量adder(4, 5)

由于我们的操作符是错误的,adder函数执行4 - 5而不是预期的4 + 59这就是为什么我们得到的不是 的期望值-1。Cargo 注意到了这一点,因此它提出了一个失败的测试。

失败的测试报告下方是它的摘要(有点),仍在failures类别下,但只是列出了失败的测试功能的名称。

最后,整体测试的完整摘要:

  • 状态是:test result: FAILED
  • 0 通过
  • 1 失败
  • 0 忽略
  • 0 测量
  • 0 过滤掉

这一次,我们的failed计数器是1(指我们失败的测试函数),而passedis 0

如何处理预期错误

从上一节中,您了解到错误会导致测试失败。

但是,如果您期望您正在测试的代码会失败(例如,给它一个无效的参数)怎么办。如果它出现错误,即使您实际上预计它会失败,cargo 也会将此标记为失败的测试。

你能期待失败的行为吗?

简短的回答是:是的,你可以!

为了证明这一点,让我们回到lib.rs文件并修改我们的adder函数。这一次,让我们为它设置一个规则,让它只接受个位数的整数(正、零和负)——否则,它应该“恐慌”。为了便于阅读,让我们将adder函数重命名为single_digit_adder.

// src/lib.rs

// modify the `adder` function from earlier
// and turn it into `single_digit_adder`
pub fn single_digit_adder(x: i8, y: i8) -> i8 {
    fn is_single_digit(x: i8) -> bool {
        x < 10 && x > -10
    }

    if !(is_single_digit(x)) || !(is_single_digit(y)) {
        panic!("Only single digit integers are allowed!");
    } else {
        x + y
    }
}

#[cfg(test)]
mod tests {
// --snip--

一个严格的函数,会因无效参数而恐慌

由于我们希望single_digit_adder函数在收到非一位整数时“恐慌”,因此我们需要在负责准确测试此行为的测试函数上指定它。

为此,我们需要向其中一个测试函数添加另一个属性。这就是#[should_panic]属性。

回到tests模块,首先,通过将函数调用it_adds重命名为.addersingle_digit_adder

然后,创建一个以it_should_only_accept_single_digitsthe#[test]#[should_panic]属性命名的新测试函数。

在这个新的测试函数中,在这种情况下single_digit_adder使用无效参数 ( ) 调用该函数。11

// src/lib.rs

pub fn single_digit_adder(x: i8, y: i8) -> i8 {
    // ...
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_adds() {
        let sum = single_digit_adder(2, 3);
        assert_eq!(sum, 5);
    }

    // our new test function that expects `panic!` with invalid param
    #[test]
    #[should_panic]
    fn it_should_only_accept_single_digits() {
        single_digit_adder(11, 4);
    }
}

预期失败行为的测试用例

您不需要在it_should_only_accept_single_digits测试函数中使用任何断言宏,因为我们只需要single_digit_adder“恐慌”。所以简单地调用函数就足够了。

通过给它一个无效的参数(11,它不是一个数字),我们期望它“恐慌”。然后,该属性将期望测试函数#[should_panic]内部出现恐慌。it_should_only_accept_single_digits如果它没有引起任何恐慌,则此测试将失败。它只会在single_digit_adder恐慌时通过。

因此,要测试它是否真的有效,请先尝试评论该#[should_panic]属性,然后运行cargo test​​. 你应该预料到它会失败。

6

现在,取消注释#[should_panic]属性并重新运行测试。您的测试应该都按预期通过:

5

期望并实际捕获失败行为的测试用例的输出

请注意,在 test旁边tests::it_should_only_accept_single_digits有一个should panic,并且它通过了测试。这意味着这个测试函数如预期的那样发生了恐慌。

你有它!您刚刚了解了什么是单元测试以及如何使用 Rust 编程语言执行单元测试。随意使用您从本文中获得的知识编写自己的测试,并将其用于您未来的项目中。

结论

在本文中,您了解了单元测试是什么以及它在软件开发过程中的重要性。您还学习了如何通过简单的三步过程编写单元测试,并在 Rust 编程语言中实际执行测试。

我们介绍了 Rust 中测试模块的结构以及如何构造测试函数,然后我们编写了一个简单的 Rust 程序和一些测试用例。我们还介绍了失败的测试以及如何在代码单元中处理预期的失败行为。

测试是软件开发过程的重要组成部分。测试您的代码有助于确保软件按预期工作。作为开发人员,测试代码以确保您交付的软件的质量以及这些愚蠢的错误不会到达最终用户是很重要的!

 来源:https ://www.freecodecamp.org/news/unit-testing-in-rust/

#rust 

What is GEEK

Buddha Community

如何在 Rust 中执行单元测试

Serde Rust: Serialization Framework for Rust

Serde

*Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.*

You may be looking for:

Serde in action

Click to show Cargo.toml. Run this code in the playground.

[dependencies]

# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }

# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"

 

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}

Getting help

Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

Download Details:
Author: serde-rs
Source Code: https://github.com/serde-rs/serde
License: View license

#rust  #rustlang 

Awesome  Rust

Awesome Rust

1654894080

Serde JSON: JSON Support for Serde Framework

Serde JSON

Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.

[dependencies]
serde_json = "1.0"

You may be looking for:

JSON is a ubiquitous open-standard format that uses human-readable text to transmit data objects consisting of key-value pairs.

{
    "name": "John Doe",
    "age": 43,
    "address": {
        "street": "10 Downing Street",
        "city": "London"
    },
    "phones": [
        "+44 1234567",
        "+44 2345678"
    ]
}

There are three common ways that you might find yourself needing to work with JSON data in Rust.

  • As text data. An unprocessed string of JSON data that you receive on an HTTP endpoint, read from a file, or prepare to send to a remote server.
  • As an untyped or loosely typed representation. Maybe you want to check that some JSON data is valid before passing it on, but without knowing the structure of what it contains. Or you want to do very basic manipulations like insert a key in a particular spot.
  • As a strongly typed Rust data structure. When you expect all or most of your data to conform to a particular structure and want to get real work done without JSON's loosey-goosey nature tripping you up.

Serde JSON provides efficient, flexible, safe ways of converting data between each of these representations.

Operating on untyped JSON values

Any valid JSON data can be manipulated in the following recursive enum representation. This data structure is serde_json::Value.

enum Value {
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(Map<String, Value>),
}

A string of JSON data can be parsed into a serde_json::Value by the serde_json::from_str function. There is also from_slice for parsing from a byte slice &[u8] and from_reader for parsing from any io::Read like a File or a TCP stream.

use serde_json::{Result, Value};

fn untyped_example() -> Result<()> {
    // Some JSON input data as a &str. Maybe this comes from the user.
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // Parse the string of data into serde_json::Value.
    let v: Value = serde_json::from_str(data)?;

    // Access parts of the data by indexing with square brackets.
    println!("Please call {} at the number {}", v["name"], v["phones"][0]);

    Ok(())
}

The result of square bracket indexing like v["name"] is a borrow of the data at that index, so the type is &Value. A JSON map can be indexed with string keys, while a JSON array can be indexed with integer keys. If the type of the data is not right for the type with which it is being indexed, or if a map does not contain the key being indexed, or if the index into a vector is out of bounds, the returned element is Value::Null.

When a Value is printed, it is printed as a JSON string. So in the code above, the output looks like Please call "John Doe" at the number "+44 1234567". The quotation marks appear because v["name"] is a &Value containing a JSON string and its JSON representation is "John Doe". Printing as a plain string without quotation marks involves converting from a JSON string to a Rust string with as_str() or avoiding the use of Value as described in the following section.

The Value representation is sufficient for very basic tasks but can be tedious to work with for anything more significant. Error handling is verbose to implement correctly, for example imagine trying to detect the presence of unrecognized fields in the input data. The compiler is powerless to help you when you make a mistake, for example imagine typoing v["name"] as v["nmae"] in one of the dozens of places it is used in your code.

Parsing JSON as strongly typed data structures

Serde provides a powerful way of mapping JSON data into Rust data structures largely automatically.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

fn typed_example() -> Result<()> {
    // Some JSON input data as a &str. Maybe this comes from the user.
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // Parse the string of data into a Person object. This is exactly the
    // same function as the one that produced serde_json::Value above, but
    // now we are asking it for a Person as output.
    let p: Person = serde_json::from_str(data)?;

    // Do things just like with any other Rust data structure.
    println!("Please call {} at the number {}", p.name, p.phones[0]);

    Ok(())
}

This is the same serde_json::from_str function as before, but this time we assign the return value to a variable of type Person so Serde will automatically interpret the input data as a Person and produce informative error messages if the layout does not conform to what a Person is expected to look like.

Any type that implements Serde's Deserialize trait can be deserialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<K, V>, as well as any structs or enums annotated with #[derive(Deserialize)].

Once we have p of type Person, our IDE and the Rust compiler can help us use it correctly like they do for any other Rust code. The IDE can autocomplete field names to prevent typos, which was impossible in the serde_json::Value representation. And the Rust compiler can check that when we write p.phones[0], then p.phones is guaranteed to be a Vec<String> so indexing into it makes sense and produces a String.

The necessary setup for using Serde's derive macros is explained on the Using derive page of the Serde site.

Constructing JSON values

Serde JSON provides a json! macro to build serde_json::Value objects with very natural JSON syntax.

use serde_json::json;

fn main() {
    // The type of `john` is `serde_json::Value`
    let john = json!({
        "name": "John Doe",
        "age": 43,
        "phones": [
            "+44 1234567",
            "+44 2345678"
        ]
    });

    println!("first phone number: {}", john["phones"][0]);

    // Convert to a string of JSON and print it out
    println!("{}", john.to_string());
}

The Value::to_string() function converts a serde_json::Value into a String of JSON text.

One neat thing about the json! macro is that variables and expressions can be interpolated directly into the JSON value as you are building it. Serde will check at compile time that the value you are interpolating is able to be represented as JSON.

let full_name = "John Doe";
let age_last_year = 42;

// The type of `john` is `serde_json::Value`
let john = json!({
    "name": full_name,
    "age": age_last_year + 1,
    "phones": [
        format!("+44 {}", random_phone())
    ]
});

This is amazingly convenient, but we have the problem we had before with Value: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSON provides a better way of serializing strongly-typed data structures into JSON text.

Creating JSON by serializing data structures

A data structure can be converted to a JSON string by serde_json::to_string. There is also serde_json::to_vec which serializes to a Vec<u8> and serde_json::to_writer which serializes to any io::Write such as a File or a TCP stream.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
}

fn print_an_address() -> Result<()> {
    // Some data structure.
    let address = Address {
        street: "10 Downing Street".to_owned(),
        city: "London".to_owned(),
    };

    // Serialize it to a JSON string.
    let j = serde_json::to_string(&address)?;

    // Print, write to a file, or send to an HTTP server.
    println!("{}", j);

    Ok(())
}

Any type that implements Serde's Serialize trait can be serialized this way. This includes built-in Rust standard library types like Vec<T> and HashMap<K, V>, as well as any structs or enums annotated with #[derive(Serialize)].

Performance

It is fast. You should expect in the ballpark of 500 to 1000 megabytes per second deserialization and 600 to 900 megabytes per second serialization, depending on the characteristics of your data. This is competitive with the fastest C and C++ JSON libraries or even 30% faster for many use cases. Benchmarks live in the serde-rs/json-benchmark repo.

Getting help

Serde is one of the most widely used Rust libraries, so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo, but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

No-std support

As long as there is a memory allocator, it is possible to use serde_json without the rest of the Rust standard library. This is supported on Rust 1.36+. Disable the default "std" feature and enable the "alloc" feature:

[dependencies]
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }

For JSON support in Serde without a memory allocator, please see the serde-json-core crate.

Link: https://crates.io/crates/serde_json

#rust  #rustlang  #encode   #json 

Rust Lang Course For Beginner In 2021: Guessing Game

 What we learn in this chapter:
- Rust number types and their default
- First exposure to #Rust modules and the std::io module to read input from the terminal
- Rust Variable Shadowing
- Rust Loop keyword
- Rust if/else
- First exposure to #Rust match keyword

=== Content:
00:00 - Intro & Setup
02:11 - The Plan
03:04 - Variable Secret
04:03 - Number Types
05:45 - Mutability recap
06:22 - Ask the user
07:45 - First intro to module std::io
08:29 - Rust naming conventions
09:22 - Read user input io:stdin().read_line(&mut guess)
12:46 - Break & Understand
14:20 - Parse string to number
17:10 - Variable Shadowing
18:46 - If / Else - You Win, You Loose
19:28 - Loop
20:38 - Match
23:19 - Random with rand
26:35 - Run it all
27:09 - Conclusion and next episode

#rust 

Lydia  Kessler

Lydia Kessler

1626318000

ULTIMATE Rust Lang Tutorial! - Publishing a Rust Crate

The ultimate Rust lang tutorial. Follow along as we go through the Rust lang book chapter by chapter.

📝Get the FREE Rust Cheatsheet: https://letsgetrusty.com/cheatsheet

The Rust book: https://doc.rust-lang.org/stable/book/​​

Chapters:
0:00​ Intro
0:43 Release Profiles
3:00 Documentation Comments
4:32 Commonly Used Sections
5:04 Documentation Comments as Tests
5:50 Commenting Contained Items
6:29 Exporting a Public API
8:44 Setting up Creates.io Account
9:54 Adding Metadata to a New Create
12:14 Publishing to Crates.io
12:49 Removing Version from Crates.io
13:37 Outro

#letsgetrusty​​ #rust​lang​ #tutorial

#rust #rust lang #rust crate

Malvina  O'Hara

Malvina O'Hara

1591266840

Rust Casting, Shadowing, Consts and Static

A mix of topics of casting, shadowing, constants and static variables inside the Rust Programming Language.

This Rust programming language tutorial series is aimed at easing your training step by step. Rust is a systems level language aimed at speed and safety and can be run cross-platform, including embedded systems and even the browser with WebAssembly (WASM)!

#rust #rust casting #rust programming