{"id":15032025,"url":"https://github.com/sr2ds/learning-rust","last_synced_at":"2026-03-11T23:36:07.715Z","repository":{"id":127378528,"uuid":"358919694","full_name":"sr2ds/learning-rust","owner":"sr2ds","description":" 🦀 📚 🧑‍🎓 Aprendendo Rust | Learning Rust  - Personal Studies about Rust Language","archived":false,"fork":false,"pushed_at":"2023-08-10T19:26:03.000Z","size":7795,"stargazers_count":9,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-09T21:40:34.222Z","etag":null,"topics":["learning","learning-rust","linguagem-rust","rust","rust-lang","rust-language"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sr2ds.png","metadata":{"files":{"readme":"Readme-us.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-04-17T15:50:37.000Z","updated_at":"2024-11-23T16:33:46.000Z","dependencies_parsed_at":null,"dependency_job_id":"2317e30f-2f69-40c1-adf2-6428019ee499","html_url":"https://github.com/sr2ds/learning-rust","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sr2ds/learning-rust","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sr2ds%2Flearning-rust","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sr2ds%2Flearning-rust/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sr2ds%2Flearning-rust/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sr2ds%2Flearning-rust/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sr2ds","download_url":"https://codeload.github.com/sr2ds/learning-rust/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sr2ds%2Flearning-rust/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30407158,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-11T22:36:59.286Z","status":"ssl_error","status_checked_at":"2026-03-11T22:36:57.544Z","response_time":84,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["learning","learning-rust","linguagem-rust","rust","rust-lang","rust-language"],"created_at":"2024-09-24T20:17:08.634Z","updated_at":"2026-03-11T23:36:02.707Z","avatar_url":"https://github.com/sr2ds.png","language":"Rust","readme":"# Learning Rust 🦀 📚 🧑‍🎓\n\n\u003cdiv align=\"center\"\u003e\n    \u003cimg src=\"assets/rust-language-logo.jpg\" width=\"30%\"\u003e \n\u003c/div\u003e\n\n🇧🇷 🇧🇷 Se você quer ler em Português do Brasil, [veja este link](Readme.md). 🇧🇷 🇧🇷\n\nThis yet is one auto translate but I'm go to revised be soon :)\n\nThis repository served to support my initial studies of the Rust language and I will be happy if it helps you as complementary content to your own studies.\n\nMy intention is to learn another language that is different from the ones I work on daily, which are of a high level.\n\nThe studies were carried out based on reading the book - [PT-BR First steps with the Rust language - José Augusto N. G. Manzano](https://amzn.to/3dBDBF1).\n\nI have a few years of experience with technology, so this will not be exactly from scratch. Except for the fact that I didn't have any contact with Rust until the beginning of the project, I just kept my curiosity and organized myself to start studying and testing.\n\nMy learning flow was with pomodóro sessions, alternating between focused reading + remembering the content I just read + creating explanatory text about what I understood. At the beginning, the simplest chapters made the whole process in a few hours, but over time it became more complex and there are chapters that I spent 1 or 2 weeks studying.\n\nThis method is part of what I learned in the book \"Learning how to learn - Barbara Oakley\".\n\nI like studying with this background playlist: https://music.youtube.com/watch?v=BMuknRb7woc\u0026feature=share\n\nPomodóro Timer: https://gnomepomodoro.org/\n\n# List Of Contents\n\n[Chapter 01 - Rust Language](#01-lingua-rust)\n\n[Chapter 02 - Sequential Action](#02-sequential-action)\n\n[Chapter 03 - Conditional Deviation](#03-conditional-deviation)\n\n[Chapter 04 - Ties](#04-Ties)\n\n[Chapter 05 - Subroutines](#05-subroutines)\n\n[Chapter 06 - Add-ons](#06-Add-ons)\n\n[Chapter 07 - Homogeneous structures](#07-homogeneous-structures)\n\n[Chapter 08 - Heterogeneous structures](#08-heterogeneous-structures)\n\n[Chapter 09 - Supplements](#09-supplements)\n\n[How to contribute](#contribute)\n\nEdit 1: On the third Wednesday, I had already read the book for other scattered days, and also practiced the exercises. This will end up being a weekly effort because I’m mega excited, but when the week tightens up, I’ll only do it on Wednesday, as agreed 🙋\n\nEdit 2: I'm in chapter 4 and I don't intend to do all the exercises from now on, just to explore the really new things (for me) of language behavior.\n\nEdit 3: I'm in chapter 6 and started practicing on some small projects, check my git.\n\nPunctual feedback: Going beyond the half of the book, I can already say that the content is legal and simple to understand.\nI cannot say that you will be ready to be a `Rust Developer` just with this reading, for that you will need to put into practice what you are learning in other contexts, mainly to understand the patterns used in large projects, as well as to explore the powers of libraries internal. But the book already gives an initial kick off.\n\n# 01 Rust Language\n\nIt was initially developed by a member of the Firefox Reaseach team, in 2010 Firefox adopted it and is now maintained also by the Firefox team (not just the initial member).\n\nRust is extremely performative, like Assembly, but it also provides a good development experience, like high level languages.\n\nRust is a compiled, safe language and you can use several paradigms to develop it.\n\nIt does not use (or has) a garbage collector (Garbage Collector) as in other languages. In Rust, this is done automatically, native to the language. I honestly don't understand it clearly yet, although I have a good idea, in the scenarios I work in there is not such a concern with memory usage at such a low level, that's one of the reasons why I want to learn Rust. In the future I hope to have more notions about the gains of not having a collector and being something native, let's see.\n\nThe `rustup` package is responsible for managing the versions of Rust on the machine, it brings two more packages. `Rustc`, which is the compiler itself, and` cargo`, which is the dependency manager, in the `npm` style of` nodeJs` and the composer of `php`.\n\nIn the studies folder, I will do the examples in the book and the exercises that are proposed during the study.\n\nRust has macros (I suppose they are native functions), and to use them, you need to put the! before passing parameters, same as in `studies/cap01/alo/main.rs`.\n\nI also did the examples with `cargo`, he does all the management even in the` npm init` style. Nice that he keeps things separate, for example, instead of compiling with `rustc`, I compiled with` cargo build`, and he created a `debug` directory, with the build result files. It also has a `cardo.lock`, in the style of` package-lock.json`.\n\nThe configuration files here are `TOML`, which is in the` YAML` style, doesn’t have a lot of secrets yet.\n\n# 02 Sequential Action\n\nThis chapter is bigger and has many details to be explored and tested, everything revolved around the data types of `Rust`. The primitive types, which we are used to as String, Integers, Floats and Sets.\n\nStarting with Integers, there was something very interesting to think about in relation to the memory cost that the compiler by default makes us spend because when no type is assigned, the compiler makes the inference natively, in the case of an integer, it will be defined as i32 . Which is a 32b integer.\n\nThe inference scheme is pretty cool, as it doesn’t force us to exactly type everything, but it’s impossible not to want to type and ensure that it looks as we can predict. In this chapter I understood that, a little bit of what makes `Rust` a safe language in terms of memory usage, is the fact that the compiler 'forces' the programmer not to commit vacillations that are very expensive in terms of computing. But it is a caveat that if you never type the integers ever, they will all be i32, when in fact, maybe you just need an i8.\n\nI'm going to set up the table here, just like it's done in the book. When it is a signed integer, it means that it can be negative.\n\n|Sinalizado| Não Sinalizado| Tamanho |\n-|--|--\n|i8 de -127 a 128 | u8 de 0 a 255 | 1 byte (8 bits) |\n|i16 de -32.768 a 32.767 | u16 de 0 65.535 | 16 bytes |\n|i32 de -2.147.483.648 a 2,147.483.647| u32  de 0 a 4.292.967.295 |32 bytes|\n|i64 de -9.223.372.036.854.775.808 a 9.223.372.036.854.775.807 | u64  de 0 a 18.446.744.073.709.551.165|64 bytes|\n|isize|usize| arch|\n\nI had thought that there could be advantages in relation to the difference between the signaled and the non-signaled, however, apparently there is no difference in terms of memory consumption. Bearing in mind that, when there is no signage, consumption is the same because the size doubles positively.\nOf course, it is also useful in case of shielding the parameter pass if negative is not an acceptable option.\n\nIn the cases of usize and isize, it will be defined according to the architecture of the processor, always in the largest size. That is, when compiling on a 32b processor, your isize / usize will become an i / u32.\n\nIn this chapter there is also a table for the float, but I will not put it here.\n\nSomething very interesting that is also in this chapter, is the fact that the macro `println!` Masks the data type. That is, you can have an integer but print it in binary format, or also format the float to less numbers after the period.\n\nAs a logical data type, we have variables and constants. Here is a curious thing:\nIn JS, when declaring a variable with `let`, it is already automatically mutable. No `Rust`. By default, `let` does not allow changing the created variable, for this you need to declare with` let mut` -\u003e mutable mut.\n\nIt is also possible to define variables with types in other formats, such as binary, octal and hexadecimal.\n\nStill in the section of variables, the book shows examples on destructuring (but does not use that term), by assigning two variables with data extracted from a tuple or array.\n\nFor example:\n\n```Rust\nlet (a, b) = (1, 2)\n```\nIn the example, we created two variables and they already have the input extracted from the array as given. Being `a = 1` and` b = 1`.\nA similar example in `nodeJs` is:\n\n```js\nlet { name } = { name:'David', idade: 27 }\n```\n\nSpeaking of examples of variable definition, in `Rust` it works like this, notice that`:u8` refers to the data type.\n\n\n```Rust\nlet idade :u8 = 27 // não mutável\nlet mut idade :u8 = 27 // mutável\n```\n\nSomething very curious is the fact that `constants` do not take up space in the ram. According to the author, constants are created in the form of labels and are not instantiated in memory. This makes me think that the binary then creates a dictionary of constants that are retrieved when necessary, that is, at run time the program accesses the instruction in, perhaps, files and not in ram.\n\nThere are several mathematical constants ready for use in the standard library and they can / should be explored.\n\nFollowing were some examples of functions and arithmetic operators, but there is nothing very different from other languages.\n\nSeveral pages with examples of incoming and outgoing flow with the terminal. Examples of simple calculations with language.\n\nRegarding comments in the code, there are three ways to comment on `Rust`. Being:\n\n```Rust\n// comentário comum de linha\n\n/*\n\n Bloco de comentários\n\n*/\n\n/// # Comentário de documentação\n/// Este comentário vai para os arquivos de documentação gerados pelo 'rustdoc`\n```\n\nIn the book you haven't yet addressed the 'rustdoc' but I have already learned from other research that I did, soon the book should address it and we will talk about it again.\n\nAfter several examples of use, to close the chapter, they have a series of exercises that I will do within `studies/chap02`.\n\nPS: I will play by practicing, so don't expect exact answers to the questions in the book.\nPS: I'm tired of the exercises in chapter 2, for now. I scored 9 out of 13 and I'm going to move on to the next chapter today.\n\n# 03 Conditional Deviation\n\nThis chapter deals with (obviously) conditional branches. That is, the if and else of life.\nTo explain all this, of course, we need to talk about logical operators like \u0026\u0026 || ! and all of that was said, as well as ==! =\u003e = \u003c=.\nNothing very new at the beginning for those who are already programming logic and algorithms.\n\nA detail that is emphasized, is that it is not possible to perform a ternary operation, that if inline assigning value, example `JavaScript`:\n\n\n```js\nconst dolar = 4\nconst brasilVenceu = dolar \u003c 5 ? 'sim' : 'não'\nconsole.log(brasilVenceu)\n```\n\nIn `Rust`, it is possible to do the if inline and it does return a value, but it is less elegant:\n\n```rust \nfn main() {\n    let dolar :u8 = 4;\n    let brasil_venceu :\u0026str = if dolar \u003c5 { \"sim\" } else { \"não\" };\n    println!(\"Brasil venceu: {}\", brasil_venceu)\n}\n```\n\nAnother thing that is different and, I particularly thought it was cool, is the match. Which is something in the `switch case 'style, but different:\n\n```rust \nfn main() {\n    let dolar :u8 = 4;\n    let brasil_venceu :\u0026str = if dolar \u003c5 { \"sim\" } else { \"não\" };\n    match dolar {\n        4 =\u003e println!(\"Brasil venceu: {}\", brasil_venceu),\n        5 =\u003e println!(\"Vish: {}\", brasil_venceu),\n        6 .. 8 =\u003e println!(\"Vish: {}\", brasil_venceu), // não funciona no playground pois é experimental -\u003e números entre 6 e 8\n        9 | 10 =\u003e println!(\"Só devolvendo pros Índios: {}\", brasil_venceu),\n        _ =\u003e println!(\"Não rolou match nenhum {}\", brasil_venceu),\n    }\n    \n}\n```\n\nI found it very semantic, even more beautiful than the `switch case` and you can also call methods instead of running println right there (which is still a kk method).\n\nLater on we get into something different called `if let`. With it we can perform actions in the validation, at the time of the exercises I will understand more clearly, but the initial impression is that it is simply to validate the return of a function, something that we already do almost naturally in `JavaScript`, but I may be wrong . It will soon become clearer.\n\nReturning to the `match`, it is possible to use it as a mixture of` try catch` with `if`, so that, for example, when converting one type to another that is invalid, it is possible to treat the error without triggering panic in the program head.\n\nIt is a functional call, 'similar' to the `JavaScript` callback scheme.\n\n\n```rust \nfn main() {\n    let input :\u0026str = \"4.2\";\n    let falso_flutuante :i32;\n\n    falso_flutuante = match input.trim().parse::\u003ci32\u003e() {\n        Ok(valor) =\u003e valor, // Ok recebe o valor correto como parâmetro e retorna para o falso_flutuante\n        Err(_) =\u003e 0, // Se deu erro \"caiu no catch\", ele retorna 0 para seguir o fluxo sem panico\n    };\n\n    println!(\"Falso Flutuante receberá 0 pois não conseguiu converter 4.2 para um i32: {}\", falso_flutuante)\n}\n```\n\nYou can also do something similar with the `if let`:\n\n```rust \nfn main() {\n    let input :\u0026str = \"4.2\";\n    let falso_flutuante :i32;\n\n    if let Ok(valor) = input.trim().parse::\u003ci32\u003e() {\n        falso_flutuante = valor\n    } else {\n        falso_flutuante = 0\n    }\n\n    println!(\"Falso Flutuante receberá 0 pois não conseguiu converter 4.2 para um i32: {}\", falso_flutuante)\n}\n```\n\nFor now, I'm finding this type of match validation more semantic.\n\nThat closes chapter 3, now I go to the exercises.\n\nPS: In no exercise do I copy and paste the previous one, nor do I consult the book. I literally do it one by one. However, I got tired of making input and I'm creating a method to solve this without repeating both the treatment and the data entry. I'll keep typing everything without repeating it, but now with a method to make it easier.\nAbout creating methods, we haven't gotten to that in the book yet, but I learned here: https://doc.rust-lang.org/rust-by-example/fn.html\n\n# 04 Ties\n\nThe 'Rust' ties are, in my view, normal. There is nothing special about it except that there is no `do while`. Although I rarely / never need to use `do while` in real life.\n\nThere is a super cool loop called `loop` that doesn’t need anything to iterate and the output control must be done internally, something like this:\n\n```rust\nloop {\n    // vai rodar eternamente, a não ser que dê um break;\n}\n```\n\nAnother cool thing, but not exclusive to iterations, is the possibility of defining sequences in very simple ways such as:\n\n```rust\nfor i in 1 .. 10 {\n    // vai de 1 a 10, não precisa criar um array de [1,2,3,4...]\n}\n```\n\nThe `break` and the` continue` are normal as in other languages, there is nothing to comment on here.\n\nIn this chapter there is a guessing challenge that is simple but it is the first time that the book explores in relation to the installation and use of an external dependency, I will replicate the example in `estudos/cap04/ex-random`.\n\nAfter adding the dependency to `Cargo.toml`, you do not need to run an` npm install` as in `NodeJs`. Just run the program with `cargo run` that it already solves the list of dependencies.\n\nThis exercise is legal because in addition to dealing with the use of an external lib, it also plays with other features of the `std` and shows the use of the` loop`.\n\n# 05 Subroutines\n\nThis chapter discusses what we generalize for 'functions' on a daily basis, but it is super cool to resume these concepts that we end up forgetting in the course of work.\n\nNot everything that is a function is a function. When there is a return, it is a function. When there is none, it is a procedure.\n\nWith `Rust`, even if you don’t choose to follow object orientation, we can develop in bottom-up. That is, start with the subroutines and only then call them. Or also do the opposite (which even makes more sense in the example), develop `main ()` with the calls of the subroutines that don't even exist yet.\n\nWe do not create functions for the day-to-day, we usually create to be able to reuse the code and also to be able to abstract the complexity.\nTo solve very complex problems, a better way to do this is to break this big problem into several smaller ones, this makes the logical solution process simpler and also allows us to create healthy automated testing mechanisms.\n\nA suggestion from the author, which I liked, is to have a kind of styleguide about when to create another subroutine, for example, if the logic has passed X lines, it should be divided.\n\nSubroutines are sequential, executed synchronously. For parallelism and asynchronicity, we use coroutines. Also known as `async / await` but we don't have any examples of that in the book yet.\n\nOne cool thing is that we have to type the function return, see an example of a function that I already did in the exercises:\n\n```rust\nfn get_i32() -\u003e i32 {\n    println!(\"Entre com o valor para adivinhação: \");\n    let mut input = String::new();\n    let number :i32;\n \n    io::stdout().flush().unwrap();\n    io::stdin().read_line(\u0026mut input).unwrap();\n    number = match input.trim().parse::\u003ci32\u003e() {\n        Ok(valor) =\u003e valor,\n        Err(_) =\u003e 0,\n    };\n    return number\n}\n```\nNote that `-\u003e i32` is the definition of the type of return that this function has to return. If you try to return something of another type, the compiler will warn you.\n\nRegarding the scope and visibility of variables and constants, the author recommends declaring constants at a global scope level, the real reason for this has not yet been explained, but I believe that when we get to ownership and bowrring I will know a little more.\n\nIn `Rust` we can close an exclusive scope even if within an apparently global place, something like this:\n\n```rust\nfn main() {\n    let exemplo_global :i32 = 99;\n    {\n        let numero_isolado :i32 = 12; // só tem visibilidade dentro do { }\n        println!(\"Acesso a varíavel de fora {}\", exemplo_global);\n    }\n    println!(\"Isso causará erro {}\", numero_isolado); // não está acessível aqui\n}\n```\n\nThe above code returns an error saying that `isolated_number` was not found in this scope, but note that what was defined above has visibility within` {} `.\n\nRegarding the definition of a 'procedure', or function with no return, it is simple, just do not have the `return`, which also makes it not necessary to specify the type of return, as I did above with` -\u003e i32` .\n\nIt is not mandatory to use the word `return` to return something, you can simply write the name of the variable and that's it, something like this:\n\n```rust\nfn get_i32() -\u003e i32 {\n    println!(\"Entre com o valor para adivinhação: \");\n    let mut input = String::new();\n    let number :i32;\n \n    io::stdout().flush().unwrap();\n    io::stdin().read_line(\u0026mut input).unwrap();\n    number = match input.trim().parse::\u003ci32\u003e() {\n        Ok(valor) =\u003e valor,\n        Err(_) =\u003e 0,\n    };\n    \n    number // Não pode ter ponto e vírgula nesse caso, isso é um exemplo de retorno sem uso da palavra return\n}\n```\n\nThe author gives some examples about variable declaration with routine, something like:\n\n```rust\nfn main() {\n    let meu_get = get_i32; // define o valor de meu_get como a chamada da sub rotina\n}\n\nfn get_i32() -\u003e i32 {\n   // ...\n}\n```\n\nWhich can also be done with inference, something more robust and taking advantage of the types:\n\n```rust\nfn main() {\n    let meu_get = fn(i32) -\u003e i32 = get_i32; // define o valor de meu_get como a chamada da sub rotina\n}\n\nfn get_i32() -\u003e i32 {\n   // ...\n}\n```\n\nIn the example below we will see about receiving a routine parameter in a function:\n\n```rust\nfn convert_i64_from_i32(num :i64) -\u003e i32 {\n}\n\nfn get_i64_and_return_i32(subrotina: fn(i64) -\u003e i32) -\u003e i32 {\n   // essa função aguarda como parâmetro uma rotina e os tipos de entrada e saída já declarados\n}\n```\nIt is possible to write `closures` with` Rust`, also called closed function and / or anonymous function, see two examples where the variable `successor` receives a parameter` i32` and returns it + 1.\n\n\n```rust\nlet incrementador = | x :i32 | { x + 1 };\nincrementador(1);\n```\n\n```rust\nlet incrementador = | x :i32 | x + 1;\nincrementador(1);\n```\n\nWe can also define the type of return:\n\n```rust\nlet incrementador = | x :i32 -\u003e i32 | x + 1;\nincrementador(1);\n```\n\nFor a clearer view, this can happen as an example of a complete function, with complex rules and line breaks:\n\n```rust\nlet incrementador = | x :i32 -\u003e i32 | {\n    let valor_incremento :i32 = 1;\n    let valor_incrementado :i32 = x + valor_incremento;\n    return valor_incrementado\n}\n\nincrementador(1);\n```\n# 06 Add-ons\n\nThis chapter covers several topics that are important in the language, starting with type conversion.\n\nThe `Rust` compiler does not convert types for you, this needs to be done explicitly. Therefore, dealing with types needs to be something natural in the mind of the `Rust` programmer. The first example of conversion, is one that I even used in some exercise, which is the magic word `as`.\n\n```rust\nlet numero64 :i64 = 100;\nlet numero32 :i32 = numero64 as i32;\n```\n\nIn this way, you are creating an i32 variable from an i64 and converting it during the declaration.\n\nThere are precautions that need to be noted in these conversions, after all you are bringing from one type to another and, many times, the source type can contemplate data larger than the destination type, as we saw in the table there in chapter 2.\n\nHere is a list of some examples of conversions using `as`:\n\n```rust\nlet valor1 = true as u8; // 1\nlet valor2 = false as u8 ; // 0\nlet valor3 = 65u8 as char; // A\nlet valor4 = -5i8 as u8; // 251\nlet valor5 = 10.99f32 as i8; // 10\nlet valor6 = 513u32 as u8; // 1 \nlet valor7 = 987u32 as u64; //987\nlet valor8 = -9i8 as i16; //-9\n```\n\nSubsequently, the sub topic addresses the types of pointers possible in `Rust`.\nIt is somewhat complex and I will try to simplify this in the elaboration of the exercises, starting with the pointers by reference, where we will have examples of the use of `\u0026` for destructuring and `*` for dereference. Honestly, I still don't know the difference in their use at the level of how it is stored in ram, the book has not yet addressed this level and maybe it won't even go.\n\nI did some tests on destructuring and dereference but I was not able to print the memory position when it is dereference, I get errors because the pointer is not implemented for the whole type, so I researched it is possible to implement this with a trait, however, I did not advance much as I haven’t seen anything about traits on `Rust` yet, so I’m going one step at a time. However, I was able to notice that the de-structuring is really about another position in ram:\n\n``\nOriginal: 10 -\u003e memory position: 0x557ed01c5000\nbreakdown value (\u0026): 10 -\u003e memory position: 0x7ffcd7124fe4\nvalue by dereference (*): 10 -\u003e I could not get a position in memory\n``\n\nNote that in the initial value and in the destructuring the positions are different. In other words, everything indicates to be another data.\n\nIn a new example, when you create the variable like this: `let value = \u0026 10i32`, with` \u0026 `, you are actually creating the value from another allocation which is 10i32.\nWithin the `change_data` method in `estudos/cap06/ex01-ref-pointers/src/main.rs` to better understand my tests, and here is the result, note that even after changing the value, the position remains the same as it should:\n\n``\nvalue is defined with mut with a value that 10 = \u0026 10i32\nvalue: 10 -\u003e memory position: 0x55dda2511038\n\u002610i32: 10 -\u003e memory position: 0x55dda2511038\nValue de-structuring: 10 -\u003e memory position: 0x7fff17ac27e0\n\nvalue will receive a new value which is 11 = \u0026 11i32\n\u002611i32: 11 -\u003e memory position: 0x55dda251103c\nvalue after change: 11 -\u003e memory position: 0x55dda251103c\nValue de-structuring after change: 11 -\u003e memory position: 0x7fff17ac27e0\n``\n\nIn the sequence, the author addressed exclusive pointers and introduced the possibility of defining variables with the fixed pointer using, `Box::new()`.\n\nI see all this in relation to the allocation of memory with good eyes, I need and I will practice because I believe that this concern really allows us to create really powerful and lean algorithms, something that in high-level languages ​​end up not even being an extreme concern as it is here in low level.\n\nIt is possible, through raw pointers, to create variables less safely in memory, here is an example of this definition:\n\nNote that to use it, it must be done in an unsafe block.\n\n```rust\nlet imutavel = 10 as *const i32;\nunsafe {\n    println!(\"{}\", imutavel);\n}\n```\n\nIt is possible to create a lib unbound from the main file, there are a few ways to do this and in this chapter the book covers creating a file, declaring it in the lib section of `Cargo.Toml` and importing it into the main. You can see an example of this in `estudos/cap06/ex03-creating-lib`, nothing complex, it is just the lib import test. There is also how to develop as a 'mod', but it has not yet been mentioned in the book.\n\n# 07 Homogeneous structures\n\nThis chapter covers the structure of several types of arrays / arrays, search and ordering. The examples are very complete even for those who are not programming, I will try to summarize by topic with emphasis on the particularities of `Rust`.\n\n## Static Matrix\n\nWe call it a static matrix when we previously know the size (dimension) that we are going to use. That is, if you need an array of 10 positions, you already declare it with 10 positions and this is a static matrix.\nWhether this array is populated by user interaction or by programming, as long as the size is fixed, it is a static matrix.\n\nIt is also important to note that the data types must be the same within the matrix.\n\n### One-dimensional Matrix\n\nWhen the matrix has only one level, or a direct set of data, we call it one-dimensional.\n\nSome examples of matrix declarations in `Rust`:\n\n```rust\n\nfn main() {\n    let _a = [0; 5]; // 5 inteiros de 32 bits\n    println!(\"{:?}\", _a); // [0, 0, 0, 0, 0]\n\n    let mut _b = [0; 5]; // 5 inteiros de 32 bits mutáveis\n    println!(\"{:?}\", _b); // [0, 0, 0, 0, 0]\n\n    // arrays tipados\n    let _c: [f32; 5] = [0.; 5]; // 5 floats de 32 bits\n    println!(\"{:?}\", _c); // [0.0, 0.0, 0.0, 0.0, 0.0]\n    \n    let mut _d: [f32; 5] = [0.; 5]; // 5 floats de 32 bits mutáveis\n    println!(\"{:?}\", _d); // [0.0, 0.0, 0.0, 0.0, 0.0]\n}\n\n```\n### Two-dimensional Matrix\nWhen the matrix has more than one level we call it two-dimensional, we can say that it is an array of arrays.\n\n```rust\n\nfn main() {\n    let _f = [[0;5]; 4]; // 4 arrays de 5 posições\n    println!(\"{:?}\", _f); // [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]\n\n    let _g: [[i32;3];5] = [[10;3];5]; // 5 arrays de 3 posições populando valor 10:i32 em cada espaço\n    println!(\"{:?}\", _g); // [[10, 10, 10], [10, 10, 10], [10, 10, 10], [10, 10, 10], [10, 10, 10]]\n}\n\n```\n\n### Internal Matrix\n\nWe call it an internal matrix when the data is previously defined, and external when the data entry is done with user interaction.\n\n```rust\nfn main() {\n    let _a = [1, 2, 3]; \n    println!(\"{:?}\", _a); // [1, 2, 3]\n\n    let _b: [f32; 2] = [1.5, 1.8];\n    println!(\"{:?}\", _b); // [1.5, 1.8]\n\n    let _c_: [[[i32;3];3];5] = [[[10;3];3];5]; // 5 arrays, contendo 3 arrays de 3 posições cada, populando valor 10:i32 em cada espaço\n    println!(\"{:?}\", _c_); // [[[10, 10, 10], [10, 10, 10], [10, 10, 10]], [[10, 10, 10], [10, 10, 10], [10, 10, 10]], [[10, 10, 10], [10, 10, 10], [10, 10, 10]], [[10, 10, 10], [10, 10, 10], [10, 10, 10]], [[10, 10, 10], [10, 10, 10], [10, 10, 10]]]\n}\n```\n\n## Dynamic Matrix\n\nUnlike the static matrices we use when we already know the dimension in advance, the dynamic matrix is populated dynamically (as the name suggests). And this type of matrix, we call a vector.\n\nFor definitions of internal vectors, we rely on the help of `Box :: new ()` and for external vectors (when the data is populated with user interaction) we will have the macro `vec!`.\n\nIn relation to memory consumption, when we make the declaration of a static matrix, the compiler tries to reserve this space in ram during the life cycle of the program, in the case of a vector it is different, since the allocation of the resource is dynamic. If used well, it guarantees savings in consumption.\n\n\n```rust\n    let a = vec![0.; tamanho];\n```\n\nThe dynamic matrices follow the same line of one-dimensional and two-dimensional, what changes is that the definition is made using the macro `vec!`.\n\n## Matrix Slicing\n\nThe book covers two examples of using slice, which I will show below:\n\n```rust\n    let a = [1,2,3,4,5,6,7,8];\n    let fatiados = \u0026a[3..8]; // [4, 5, 6, 7, 8]\n    println!(\"{:?}\",  fatiados);\n    \n    let tudo = \u0026a[..];\n    println!(\"{:?}\",  tudo);  // [1,2,3,4,5,6,7,8]\n```\n\n## Ordering and Research\n\nIn `Rust` there is no native function for sorting and searching within matrices, I will do the example of basic sorting in` estudos/cap07/ex02-matrix-ordenate`.\n\nAnytime I'll get to code the ordering methods in `Rust`, how about we do this as an exercise?\n\n### Matrix Elements Search\n\nIn research, the author gives an example of a basic search with a `while` in the entire matrix looking for, and another example of binary search that breaks the matrix in half for the search to be faster in matrices that are ordered.\n\n## Iterators\n \nThis part of the book deals with iterators and highlights some particularities of `Rust`, such as the use of` next () `and some benefits of` iter () `.\n\nThere is a lot of content and it is really interesting, some examples are in `estudos/cap07/ex03-iterator`.\n\n\n# 08 Heterogeneous structures\n\nIf in the homogeneous structures the data that compose the matrices are of the same type, here in the heterogeneous ones it can be different.\n\nThe first topic covered is tuples. Tuples have a behavior similar to that of the array and can be used with `match`, let's see some examples:\n\n\n```rust\n    let tupla = (1, 2, \"David\", \"Silva\", \"Rust\", \"Language\");\n    println!(\"{:?}\",  tupla);\n    println!(\"{}\",  tupla.0); // 1\n    println!(\"{}\",  tupla.2); // David\n```\n\nRealize that data access is with the `.` and its position.\n\nWith match, we can do something like this:\n\n```rust\n    let tupla = (1, 2);\n\n    match tupla {\n        (1, 2) =\u003e println!(\"Print 1, 2\"),\n        _ =\u003e println!(\"Não corresponde\")\n    };\n```\n\nIt may also be possible to return a tuple directly in a subroutine.\n\nFollowing, the book discusses the uses of `struct`, with examples for the three common forms of use in the` Rust` language, namely: Classical Structure, Tuple Structure and Unit Structure.\n\nIn the first example, as a classic structure, the use of `struct` is similar to a type definition object, a mold (or shape) for creating a variable:\n\n\n``` rust\nstruct Pessoa {\n    nome: String,\n    idade: i32,\n    profissao: String,\n}\n\nfn main() {\n    let pessoa = Pessoa {\n        nome: \"David\".to_string(),\n        idade: 27,\n        profissao: \"Software Engineer\".to_string(),\n    };\n    println!(\"{}\", pessoa.nome); // David\n}\n\n```\n\nAs done above, a `struct` is made outside of` main () `, using` CamelCase` in its title and access to the data is done with `.`, similar to the tuple.\nIt is important to note that in the case of the tuple, it is not expected that the data will have a contextual connection, in the case of a struct, yes.\n\nIn the tuple structure, we use the reserved word struct as well, but with parentheses, as a tuple. And in this format, you should not pass the field names:\n\n``` rust\nstruct Idades(u8, u8);\n\nfn main() {\n    let idades = Idades(27, 28);\n    println!(\"{}\", idades.0); // 27\n    println!(\"{}\", idades.1); // 28\n}\n```\n\nAlthough possible, it does not make much sense to structure this tuple with data of a different type, this will make it difficult to use later.\n\nIn the case of unit structures, we have an example that reminds us of the use of interfaces, where we use a struct with the reserved word `impl` to abstract some subroutine, similar to the Factory pattern.\n\n\n``` rust\nstruct Animal;\nstruct Cao;\nstruct Gato;\n\nimpl Animal {\n    fn latir(\u0026self, som: \u0026Cao) -\u003e () {\n        println!(\"au au\");\n    }\n}\n\nimpl Animal {\n    fn miar(\u0026self, som: \u0026Gato) -\u003e () {\n        println!(\"miau\");\n    }\n}\n\nfn main() {\n    let pet = Animal{};\n    let cao = Cao{};\n    let gato = Gato{};\n\n    println!(\"O Gato:\"); pet.miar(\u0026gato);\n    println!(\"O Cao:\"); pet.miar(\u0026cao);\n}\n```\n\nIn the sequence, the author talks about `enum`, and below is an example about the use of` enum` in `Rust`:\n\n``` rust\nenum DDD {\n    SP = 11,\n    MG = 31\n}\n\nfn main() {\n    println!(\"DDD de São Paulo: {:?}\", DDD::SP as u8);\n    println!(\"DDD de Minas Gerais: {:?}\", DDD::MG as u8);\n}\n```\n\nThe definition of an `enum` is very similar to that of a` struct`, but access to it is with `::`.\nIt is important to point out that, in a numbered 'enum` list, you can define the first value and the next ones will be automatic additions, in the index format, for example:\n\n\n``` rust\nenum UFs {\n    SP = 10, // definir o primeiro como 10\n    MG,\n    BA,\n    RJ\n}\n\nfn main() {\n    println!(\"UFs SP {:?}\", UFs::SP as u8);\n    println!(\"UFs MG {:?}\", UFs::MG as u8); // automáticamente este é 11 e assim por diante\n}\n```\n\nThe combined use of `enum` and` scruct` allows us to inherit behaviors that we are used to object orientation, see a simple and practical example.\n\n``` rust\n#[derive(Debug)]\nenum Profession {\n    Developer,\n    Architect,\n    Engineer,\n}\n\nstruct People {\n    name: String,\n    age: u8,\n    profession: Profession,\n}\n\nfn main() {\n    let people = People {\n        name: \"David\".to_string(),\n        age: 27,\n        profession: Profession::Engineer,\n    };\n\n    println!(\"People name: {:?}\", people.name);\n    println!(\"People age: {:?}\", people.age);\n    println!(\"People profession: {:?}\", people.profession); // é necessário setar o derive(Debug) na enum para dar print assim\n}\n\n```\nThe author addresses in a very detailed way about the ways of implementing object orientation with `Rust`, getter / setter structure, polymorphism, object instance, etc. In these examples he addresses about the` traits` and replicates an example about the behavior of the OOP with `trait` and` struct`. I will not go into this detail here now, maybe I will come back later and refactor, but for now I will continue.\n\n# 09 Supplements\n\nThis chapter begins by addressing the use of generic types with `T`. That I really had no idea what it was until now, and it's clearer now.\n\nWhen declaring T as the type of a subroutine, it starts to receive parameters of any type. You don't necessarily need to call it T, you can use any uppercase name to make it work.\n\nIt is important to note that for certain operations to work it is necessary to implement something with the T and in fact it makes sense because how will you, for example, compare two values ​​if there is no implementation of any kind in them?\n\n\n# How to Contribute\n\nContributions are welcome! If you want to correct some text, revise an implementation or even give better examples in relation to some content, feel free. Just send a Pull Request :)","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsr2ds%2Flearning-rust","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsr2ds%2Flearning-rust","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsr2ds%2Flearning-rust/lists"}