diff --git a/.gitignore b/.gitignore index 551225c..9ffa1d8 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ hugo.yaml .hugo_build.lock .gitmodules -/docs /data /themes /static \ No newline at end of file diff --git a/content/en/docs/a2.installation.md b/content/en/docs/a2.installation.md index b0eaefe..06d230e 100755 --- a/content/en/docs/a2.installation.md +++ b/content/en/docs/a2.installation.md @@ -32,7 +32,7 @@ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ### For Windows Users Download **`rustup-init.exe`** from [www.rustup.rs](https://rustup.rs/) and run. -> πŸ’‘ You may need to install [Visual C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) 2015 or higher, which requires an additional 3–4 GBs. +> πŸ’‘ You may need to install [Visual C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) 2019 or higher, which requires an additional 3–4 GBs. ## πŸ‘¨β€πŸ« Before going to the next... diff --git a/docs/assets/css/docs.min.8e9408609771a441499aa5571a4585b0ca95783b842d5c758af5eef1457b0fe0.css b/docs/assets/css/docs.min.8e9408609771a441499aa5571a4585b0ca95783b842d5c758af5eef1457b0fe0.css new file mode 100644 index 0000000..bd38649 --- /dev/null +++ b/docs/assets/css/docs.min.8e9408609771a441499aa5571a4585b0ca95783b842d5c758af5eef1457b0fe0.css @@ -0,0 +1 @@ +*:where(:not(html,iframe,canvas,img,svg,video,audio,pre,code):not(svg *,symbol *)){all:unset;display:revert}*,*::before,*::after{box-sizing:border-box}html{-moz-text-size-adjust:none;-webkit-text-size-adjust:none;text-size-adjust:none}a,button{cursor:revert}ol,ul,menu,summary{list-style:none}img{max-inline-size:100%;max-block-size:100%}table{border-collapse:collapse}input,textarea{-webkit-user-select:auto}textarea{white-space:revert}meter{-webkit-appearance:revert;appearance:revert}:where(pre){all:revert;box-sizing:border-box}::placeholder{color:unset}::marker{content:initial}:where([hidden]){display:none}:where([contenteditable]:not([contenteditable=false])){-moz-user-modify:read-write;-webkit-user-modify:read-write;overflow-wrap:break-word;-webkit-line-break:after-white-space;-webkit-user-select:auto}:where([draggable=true]){-webkit-user-drag:element}:where(dialog:modal){all:revert;box-sizing:border-box}pre,code{margin:0}::-webkit-details-marker{display:none}:root{--font-sans:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--font-brand:"Arial", serif;--color:rgba(0, 0, 0, 1);--color-fade:rgba(0, 0, 0, .54);--color-nav:rgba(0, 0, 0, .7);--background:#ffffff;--background-grey:#f9f9f9;--background-grey-embed:#f0f0f0;--foreground:rgba(247, 247, 247, .25);--foreground-hover:rgba(220, 220, 220, .35);--foreground-highlight:#f5d41f;--color-highlight:#130606;--model-background:#ffffff;--model-foreground:rgba(247, 247, 247, .25);--model-box-shadow:0 8px 32px 0 rgba(31, 38, 135, .37);--padding:12px;--padding_d2:6px;--padding_x2:24px;--model-blur:10px;--border:#efefef;--border-nav:#dddddd;--radius:4px;--anchor:#235ce8;--hover:#547ce3;--chroma-base00:#f9f9f9;--chroma-base01:#e0e0e0;--chroma-base02:rgba(159, 218, 159, .2);--chroma-base03:#8e908c;--chroma-base04:#969896;--chroma-base05:#4d4d4c;--chroma-base06:#282a2e;--chroma-base07:#1d1f21;--chroma-base08:#c82829;--chroma-base09:#f5871f;--chroma-base0A:#eab700;--chroma-base0B:#718c00;--chroma-base0C:#3e999f;--chroma-base0D:#4271ae;--chroma-base0E:#8959a8;--chroma-base0F:#a3685a;--callout-info-backgound:#954ce3;--callout-info-foreground:rgba(0, 0, 0, .08);--callout-info-color:#ffffff;--callout-info-anchor:#d2aefc;--callout-info-anchor-text-shadow:.4px 0 .8px black}:root[data-color=dark]{--color:rgba(255, 255, 255, 1);--color-fade:rgba(255, 255, 255, .5);--color-nav:rgba(255, 255, 255, .8);--background:#101010;--background-grey:#1e1e1e;--background-grey-embed:#2f2d2d;--foreground:rgba(19, 19, 19, 1);--foreground-hover:rgba(35, 35, 35, 1);--model-background:rgba(16, 16, 16, 1);--model-foreground:rgba(225, 225, 225, .05);--model-box-shadow:0 8px 32px 0 rgba(241, 235, 235, 0.1);--border:rgba(225, 225, 225, .1);--border-nav:rgba(255, 255, 255, .2);--anchor:#2e87f1;--hover:#044b9d;--chroma-base00:var(--background-grey);--chroma-base01:#393939;--chroma-base02:rgba(159, 218, 159, .1);--chroma-base03:#999999;--chroma-base04:#b4b7b4;--chroma-base05:#cccccc;--chroma-base06:#e0e0e0;--chroma-base07:#ffffff;--chroma-base08:#f2777a;--chroma-base09:#f99157;--chroma-base0A:#ffcc66;--chroma-base0B:#99cc99;--chroma-base0C:#66cccc;--chroma-base0D:#6699cc;--chroma-base0E:#cc99cc;--chroma-base0F:#a3685a}.site-logo{text-transform:uppercase;font-family:var(--font-brand);font-size:1.5em;color:transparent;-webkit-text-stroke:.5px var(--border);background:0 0;letter-spacing:3px;background:linear-gradient(45deg,#866ee7,#ea60da,#ed8f57,#fbd41d,#2cca91);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;font-weight:800}.btn{display:flex;padding:var(--padding_d2);background:var(--foreground);border:1px solid var(--border);border-radius:var(--radius);gap:var(--padding_d2);cursor:pointer;color:var(--color-nav)}.btn:hover{background:var(--foreground-hover)}html{scroll-behavior:smooth;scroll-padding:2em}body{display:flex;flex-direction:column;height:100%;color:var(--color);background:var(--background);font-family:var(--font-sans)}#outer-wrapper{display:flex}#aside-wrapper{width:85%;left:-85%;display:none;overflow-x:auto}#aside-wrapper>aside>div{display:flex;padding:var(--padding);justify-content:flex-end}#aside-wrapper>aside>a{display:none}#content-wrapper{display:flex;flex:1;flex-direction:column;min-height:100svh}main{display:flex;flex-direction:column;flex:1;width:100svw}#aside-wrapper.open{display:flex;flex-direction:column;position:fixed;top:0;height:100%;z-index:10;transition:.3s;animation:slide-in-left .3s forwards;background:var(--model-background);box-shadow:var(--model-box-shadow)}@keyframes slide-in-left{from{transform:translateX(0)}to{transform:translateX(100%)}}#content-wrapper>header{border-bottom:1px solid var(--border)}#content-wrapper>header>a{display:inline-block;padding:var(--padding)}#content-wrapper>footer{display:flex;flex-direction:column;padding:var(--padding)}#content-wrapper>footer>div{display:flex;align-items:center;justify-content:center;padding:var(--padding);gap:var(--padding_d2);text-align:center;flex-wrap:wrap}#content-wrapper>footer>div:first-child{white-space:initial}#content-wrapper>footer>div:first-child a{background:var(--foreground-highlight);color:var(--color-highlight);border-radius:var(--radius);cursor:pointer;padding:0 var(--padding_d2)}#content-wrapper>footer>div:nth-child(2){justify-content:flex-end}main>article{display:flex;flex:1;flex-direction:column}main>article>nav{display:flex;padding:var(--padding_x2)var(--padding)var(--padding);gap:12px;justify-content:space-between}main>article>header{padding:var(--padding)var(--padding_x2)}#article-body{display:flex;flex-direction:column;flex:1;padding:var(--padding)var(--padding_x2);overflow-x:auto}main>article>footer{display:grid;grid-template-columns:repeat(2,1fr);padding:0 var(--padding_x2)}main>article>footer>time{grid-column:1/3;display:flex;color:var(--color-fade);justify-content:center;padding:var(--padding)0;gap:var(--padding_d2)}main>article>footer>a{display:flex;padding:var(--padding);gap:calc(var(--padding)/4);background:var(--foreground);color:var(--color-nav);border:1px solid var(--border);border-radius:var(--radius);cursor:pointer;width:75%}main>article>footer>a:hover{background:var(--foreground-hover)}main>article>footer>a.hidden{visibility:hidden}main>article>footer>a:last-child{display:flex;justify-content:end;margin-left:25%}main>aside{width:85%;right:-85%;display:none;overflow-x:auto}main>aside.open{display:flex;flex-direction:column;position:fixed;top:0;height:100%;z-index:10;transition:.3s;animation:slide-in-right .3s forwards;background:var(--model-background);box-shadow:var(--model-box-shadow)}#aside-wrapper{position:sticky;top:0}#aside-wrapper>aside>nav{padding:0 var(--padding)}#aside-wrapper>aside>nav>details{padding-bottom:0}#aside-wrapper>aside>nav>details[open]{padding-bottom:calc(var(--padding) * 1.5)}#aside-wrapper>aside>nav>details>summary{display:flex;padding:var(--padding)0;color:var(--color);font-weight:700}#aside-wrapper>aside>nav>details[open]>summary{color:var(--color-fade)}#aside-wrapper>aside>nav>details>ul>li{margin:0 var(--padding_d2);border-left:1px solid var(--border-nav)}#aside-wrapper>aside>nav>details>ul>li>a{color:var(--color-nav);display:flex;cursor:pointer;padding:var(--padding_d2)}#aside-wrapper>aside>nav>details>ul>li>a::before{content:'';display:inline-block;background:var(--background);width:var(--padding_d2);height:var(--padding_d2);transform:rotate(45deg);border:1px solid var(--border-nav);position:relative;left:calc((var(--padding) * -.78));top:3px}#aside-wrapper>aside>nav>details>ul>li>a.active{background:var(--foreground-highlight);color:var(--color-highlight);border-top-right-radius:var(--radius);border-bottom-right-radius:var(--radius)}#aside-wrapper>aside>nav>details>ul>li>a.active::before{background:var(--foreground-highlight);border:var(--foreground-highlight);left:calc((var(--padding) * -.76))}#aside-wrapper>aside>nav>details>ul>li>a:hover:not(.active){background:var(--foreground-hover);border-top-right-radius:var(--radius);border-bottom-right-radius:var(--radius)}main>aside>div{display:flex;padding:var(--padding)}main>aside>strong{display:flex;padding:var(--padding);color:var(--color-fade);font-weight:700}main>aside>nav{padding:0 var(--padding)}#TableOfContents ul{border-left:1px solid var(--border)}#TableOfContents a{color:var(--color-nav);display:inline-block;cursor:pointer;padding:var(--padding_d2)}#TableOfContents a code{padding:calc(var(--padding)/3.7);border-radius:var(--radius);font-size:.9em}#TableOfContents ul a::before{content:'';display:inline-block;width:calc(var(--padding)/1.5);height:calc(var(--padding)/1.5);background:var(--background);border:1px solid var(--border-nav);position:relative;left:calc((var(--padding) * -.89));top:-3px;border-radius:30%;transform:rotate(45deg)}#TableOfContents a.active{background:var(--foreground-highlight);color:var(--color-highlight);border-top-right-radius:var(--radius);border-bottom-right-radius:var(--radius)}#TableOfContents ul a.active::before{background:var(--background)}#TableOfContents a:hover:not(.active){background:var(--foreground-hover);border-top-right-radius:var(--radius);border-bottom-right-radius:var(--radius)}#TableOfContents ul ul{margin-left:calc(var(--padding) * 1.75)}@keyframes slide-in-right{from{transform:translateX(0)}to{transform:translateX(-100%)}}body.model-open{overflow:hidden}#body-model-outer{display:none;content:"";position:fixed;top:0;left:0;width:100%;height:100%;z-index:5;background:var(--model-foreground);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)}#aside-wrapper>aside>div .btn,main>aside>div>.btn{font-size:.75em;font-weight:800}@media(min-width:768px){main>article>footer>a{width:50%}main>article>footer>a:last-child{margin-left:50%}}@media(min-width:768px) and (max-width:1023px){#aside-wrapper{width:50%;left:-50%}main>aside{width:50%;right:-50%}}@media(min-width:1024px){:root{--padding:16px;--padding_d2:8px;--padding_x2:32px}main{flex-direction:row}main>article{width:75vw;overflow-x:auto}main>aside{width:25%;display:flex;flex-direction:column;position:sticky;top:0;height:calc(100svh - 68px);overflow-x:auto}main>aside>div{display:none}main>article>nav>button:last-child{display:none}#content-wrapper>footer{padding:0 var(--padding);flex-direction:row}#content-wrapper>footer>div:first-child{width:75vw}#content-wrapper>footer>div:nth-child(2){width:25%}}@media(min-width:1024px) and (max-width:1279px){#aside-wrapper{width:33%;left:-33%}}@media(min-width:1280px){#aside-wrapper{width:20%;display:flex;flex-direction:column;height:100svh;background:var(--foreground);border-right:1px solid var(--border);overflow-x:auto}#aside-wrapper>aside>div{display:none}#aside-wrapper>aside>nav{overflow-x:auto}#content-wrapper>header{display:none}#aside-wrapper>aside>a{display:flex;padding:var(--padding_x2)var(--padding)}main{width:80svw;padding:0 var(--padding_x2)}main>article{width:60vw;overflow-x:auto}main>article>nav{display:none}main>aside{width:25%}main>article>header{padding:var(--padding_x2)var(--padding_x2)var(--padding)}#content-wrapper>footer>div:first-child{width:60vw}#content-wrapper>footer>div:nth-child(2){width:25%}}main>article>header>h1{font-size:3em}main>article>header>p{font-size:1.25em;color:var(--color-fade);padding-top:var(--padding)}#article-body h1,#article-body h2,#article-body h3,#article-body h4,#article-body h5,#article-body h6{line-height:1em;font-weight:400;margin:2.6em 0 .1em;color:var(--color)}#article-body h1{font-size:1.8em}#article-body h2{font-size:1.5em}#article-body h3{font-size:1.3em}#article-body h4{font-size:1.1em}#article-body h2:first-child{margin-top:.6em}#article-body .highlight,#article-body blockquote,#article-body dl,#article-body iframe,#article-body ol,#article-body p,#article-body table,#article-body ul{margin-top:1em;line-height:1.8rem;letter-spacing:-.1px}#article-body blockquote p{margin:1em 0}#article-body blockquote dl,#article-body blockquote ol,#article-body blockquote ul{margin:0 1em 1em}#article-body a{color:var(--anchor);text-decoration:none}#article-body a:hover{color:var(--hover);text-decoration:underline}#article-body strong,#article-body b,#article-body table th{font-weight:600}#article-body em{font-style:italic}#article-body dl,#article-body ol,#article-body ul{margin-left:20px}#article-body dl dl,#article-body dl ol,#article-body dl ul,#article-body ol dl,#article-body ol ol,#article-body ol ul,#article-body ul dl,#article-body ul ol,#article-body ul ul{margin-top:0;margin-bottom:0}#article-body ul{list-style:disc}#article-body ol{list-style:decimal}#article-body dl{list-style:square}#article-body li>ul{list-style:circle}#article-body li>ol{list-style:lower-alpha}#article-body li p{margin:0}#article-body li .highlight,#article-body li blockquote,#article-body li iframe,#article-body li table{margin:1em 0}#article-body img,#article-body video{max-width:100%;border-radius:4px}#article-body hr:before{display:block;text-align:center;content:"βˆ™ βˆ™ βˆ™";color:var(--color-fade);letter-spacing:.6em;top:calc(var(--padding)/3.7);margin:2.6em 0 1em}#article-body blockquote{padding:8px 12px;position:relative;background:var(--background-grey);border-left-width:5px;border-radius:6px}#article-body blockquote footer{margin:1em 0;font-style:italic}#article-body blockquote footer cite:before{content:"β€”";padding:0 .3em}#article-body blockquote footer cite a{color:var(--border)}#article-body code,#article-body pre{font-family:var(--font-mono)}#article-body h1 code,#article-body h2 code,#article-body h3 code,#article-body h4 code,#article-body h5 code,#article-body h6 code,#article-body p code,#article-body blockquote code,#article-body ul code,#article-body ol code,#article-body dl code,#article-body table code{background:var(--background-grey);padding:calc(var(--padding)/3.7);border-radius:var(--radius);font-size:.9em}#article-body blockquote code{background:var(--background-grey-embed)}#article-body pre:not(.chroma){color:var(--chroma-base05);font-size:.9em;line-height:1.8;letter-spacing:-.1px;background-color:var(--chroma-base00);border-radius:6px;padding:16px 24px;overflow-x:auto;margin-top:1em}#article-body blockquote .chroma,#article-body blockquote pre:not(.chroma){background:var(--foreground-hover);margin-bottom:1em}#article-body blockquote .chroma code,#article-body blockquote pre:not(.chroma) code{padding:0}#article-body table{max-width:100%;border-radius:var(--radius);box-shadow:0 0 0 1px var(--border)}#article-body table thead th:first-child{border-top-left-radius:var(--radius)}#article-body table thead th:last-child{border-top-right-radius:var(--radius)}#article-body table tbody tr:last-child{border-bottom-left-radius:var(--radius);border-bottom-right-radius:var(--radius)}#article-body table tbody tr:last-child td:first-child{border-bottom-left-radius:var(--radius)}#article-body table tbody tr:last-child td:last-child{border-bottom-right-radius:var(--radius)}#article-body table td,#article-body table th{padding:5px 15px}#article-body table tr:nth-child(2n){background:var(--background-grey)}#article-body table thead tr{background:var(--background-grey-embed)}.chroma{font-size:.9em;color:var(--chroma-base05);background-color:var(--chroma-base00);border-radius:6px;padding:16px 24px;overflow-x:auto}.chroma .x{color:var(--chroma-base05)}.chroma .err{color:var(--chroma-base08)}.chroma .lntd{vertical-align:top;padding:0;margin:0;border:0}.chroma .lntable{border-spacing:0;padding:0;margin:0;border:0;width:auto;overflow:auto;display:block}.chroma .hl{display:block;width:100%;background-color:var(--chroma-base02)}.chroma .lnt{margin-right:.4em;padding:0 .4em}.chroma .ln{margin-right:.4em;padding:0 .4em;border-right:1px solid var(--chroma-base0A)}.chroma .line{display:flex}.chroma .k{color:var(--chroma-base0E)}.chroma .kc{color:var(--chroma-base0E)}.chroma .kd{color:var(--chroma-base0E)}.chroma .kn{color:var(--chroma-base0E)}.chroma .kp{color:var(--chroma-base0D)}.chroma .kr{color:var(--chroma-base0E)}.chroma .kt{color:var(--chroma-base0E)}.chroma .n{color:var(--chroma-base05)}.chroma .na{color:var(--chroma-base05)}.chroma .nb{color:var(--chroma-base0D)}.chroma .bp{color:var(--chroma-base0D)}.chroma .nc{color:var(--chroma-base0A)}.chroma .no{color:var(--chroma-base09)}.chroma .nd{color:var(--chroma-base09)}.chroma .ni{color:var(--chroma-base0A)}.chroma .ne{color:var(--chroma-base0A)}.chroma .nf{color:var(--chroma-base05)}.chroma .fm{color:var(--chroma-base05)}.chroma .nl{color:var(--chroma-base08)}.chroma .nn{color:var(--chroma-base0A)}.chroma .nx{color:var(--chroma-base0D)}.chroma .py{color:var(--chroma-base08)}.chroma .nt{color:var(--chroma-base0D)}.chroma .nv{color:var(--chroma-base0D)}.chroma .vc{color:var(--chroma-base0D)}.chroma .vg{color:var(--chroma-base0D)}.chroma .vi{color:var(--chroma-base08)}.chroma .vm{color:var(--chroma-base0D)}.chroma .l{color:var(--chroma-base0B)}.chroma .ld{color:var(--chroma-base0B)}.chroma .s{color:var(--chroma-base0B)}.chroma .sa{color:var(--chroma-base0B)}.chroma .sb{color:var(--chroma-base0B)}.chroma .sc{color:var(--chroma-base0B)}.chroma .dl{color:var(--chroma-base0F)}.chroma .sd{color:var(--chroma-base03)}.chroma .s2{color:var(--chroma-base0B)}.chroma .se{color:var(--chroma-base0C)}.chroma .sh{color:var(--chroma-base0B)}.chroma .si{color:var(--chroma-base0F)}.chroma .sx{color:var(--chroma-base0B)}.chroma .sr{color:var(--chroma-base0C)}.chroma .s1{color:var(--chroma-base0B)}.chroma .ss{color:var(--chroma-base0B)}.chroma .m{color:var(--chroma-base09)}.chroma .mb{color:var(--chroma-base09)}.chroma .mf{color:var(--chroma-base09)}.chroma .mh{color:var(--chroma-base09)}.chroma .mi{color:var(--chroma-base09)}.chroma .il{color:var(--chroma-base09)}.chroma .mo{color:var(--chroma-base09)}.chroma .o{color:var(--chroma-base05)}.chroma .ow{color:var(--chroma-base05)}.chroma .p{color:var(--chroma-base05)}.chroma .c{color:var(--chroma-base03)}.chroma .ch{color:var(--chroma-base03)}.chroma .cm{color:var(--chroma-base03)}.chroma .c1{color:var(--chroma-base03)}.chroma .cs{color:var(--chroma-base03)}.chroma .cp{color:var(--chroma-base0F)}.chroma .cpf{color:var(--chroma-base0B)}.chroma .g{color:var(--chroma-base05)}.chroma .gd{color:var(--chroma-base08)}.chroma .ge{color:var(--chroma-base05);font-style:italic}.chroma .gr{color:var(--chroma-base05)}.chroma .gh{color:var(--chroma-base0D)}.chroma .gi{color:var(--chroma-base0B)}.chroma .go{color:var(--chroma-base05)}.chroma .gp{color:var(--chroma-base05)}.chroma .gs{color:var(--chroma-base05);font-weight:700}.chroma .gu{color:var(--chroma-base0D)}.chroma .gt{color:var(--chroma-base05)}.chroma .gl{color:var(--chroma-base05);text-decoration:underline}.chroma .w{color:var(--chroma-base00)}#article-body blockquote.info{border:none;background:var(--callout-info-backgound);color:var(--callout-info-color)}#article-body blockquote.info>p{display:flex;gap:var(--padding_d2)}#article-body blockquote.info>p:first-child>strong:first-child{font-size:2.5em}#article-body blockquote.info li{margin:0 var(--padding_d2)}#article-body blockquote.info code{background:var(--callout-info-foreground)}#article-body blockquote.info a{color:var(--callout-info-anchor);text-shadow:var(--callout-info-anchor-text-shadow)} \ No newline at end of file diff --git a/docs/assets/css/home.min.8be2cba1e2901070d4706b98c8a753a6f9eb3463918684b75e0553ca344d936d.css b/docs/assets/css/home.min.8be2cba1e2901070d4706b98c8a753a6f9eb3463918684b75e0553ca344d936d.css new file mode 100644 index 0000000..db053c5 --- /dev/null +++ b/docs/assets/css/home.min.8be2cba1e2901070d4706b98c8a753a6f9eb3463918684b75e0553ca344d936d.css @@ -0,0 +1 @@ +*:where(:not(html,iframe,canvas,img,svg,video,audio,pre,code):not(svg *,symbol *)){all:unset;display:revert}*,*::before,*::after{box-sizing:border-box}html{-moz-text-size-adjust:none;-webkit-text-size-adjust:none;text-size-adjust:none}a,button{cursor:revert}ol,ul,menu,summary{list-style:none}img{max-inline-size:100%;max-block-size:100%}table{border-collapse:collapse}input,textarea{-webkit-user-select:auto}textarea{white-space:revert}meter{-webkit-appearance:revert;appearance:revert}:where(pre){all:revert;box-sizing:border-box}::placeholder{color:unset}::marker{content:initial}:where([hidden]){display:none}:where([contenteditable]:not([contenteditable=false])){-moz-user-modify:read-write;-webkit-user-modify:read-write;overflow-wrap:break-word;-webkit-line-break:after-white-space;-webkit-user-select:auto}:where([draggable=true]){-webkit-user-drag:element}:where(dialog:modal){all:revert;box-sizing:border-box}pre,code{margin:0}::-webkit-details-marker{display:none}:root{--font-sans:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--font-brand:"Arial", serif;--color:rgba(0, 0, 0, 1);--color-fade:rgba(0, 0, 0, .54);--color-nav:rgba(0, 0, 0, .7);--background:#ffffff;--background-grey:#f9f9f9;--background-grey-embed:#f0f0f0;--foreground:rgba(247, 247, 247, .25);--foreground-hover:rgba(220, 220, 220, .35);--foreground-highlight:#f5d41f;--color-highlight:#130606;--model-background:#ffffff;--model-foreground:rgba(247, 247, 247, .25);--model-box-shadow:0 8px 32px 0 rgba(31, 38, 135, .37);--padding:12px;--padding_d2:6px;--padding_x2:24px;--model-blur:10px;--border:#efefef;--border-nav:#dddddd;--radius:4px;--anchor:#235ce8;--hover:#547ce3;--chroma-base00:#f9f9f9;--chroma-base01:#e0e0e0;--chroma-base02:rgba(159, 218, 159, .2);--chroma-base03:#8e908c;--chroma-base04:#969896;--chroma-base05:#4d4d4c;--chroma-base06:#282a2e;--chroma-base07:#1d1f21;--chroma-base08:#c82829;--chroma-base09:#f5871f;--chroma-base0A:#eab700;--chroma-base0B:#718c00;--chroma-base0C:#3e999f;--chroma-base0D:#4271ae;--chroma-base0E:#8959a8;--chroma-base0F:#a3685a;--callout-info-backgound:#954ce3;--callout-info-foreground:rgba(0, 0, 0, .08);--callout-info-color:#ffffff;--callout-info-anchor:#d2aefc;--callout-info-anchor-text-shadow:.4px 0 .8px black}:root[data-color=dark]{--color:rgba(255, 255, 255, 1);--color-fade:rgba(255, 255, 255, .5);--color-nav:rgba(255, 255, 255, .8);--background:#101010;--background-grey:#1e1e1e;--background-grey-embed:#2f2d2d;--foreground:rgba(19, 19, 19, 1);--foreground-hover:rgba(35, 35, 35, 1);--model-background:rgba(16, 16, 16, 1);--model-foreground:rgba(225, 225, 225, .05);--model-box-shadow:0 8px 32px 0 rgba(241, 235, 235, 0.1);--border:rgba(225, 225, 225, .1);--border-nav:rgba(255, 255, 255, .2);--anchor:#2e87f1;--hover:#044b9d;--chroma-base00:var(--background-grey);--chroma-base01:#393939;--chroma-base02:rgba(159, 218, 159, .1);--chroma-base03:#999999;--chroma-base04:#b4b7b4;--chroma-base05:#cccccc;--chroma-base06:#e0e0e0;--chroma-base07:#ffffff;--chroma-base08:#f2777a;--chroma-base09:#f99157;--chroma-base0A:#ffcc66;--chroma-base0B:#99cc99;--chroma-base0C:#66cccc;--chroma-base0D:#6699cc;--chroma-base0E:#cc99cc;--chroma-base0F:#a3685a}.site-logo{text-transform:uppercase;font-family:var(--font-brand);font-size:1.5em;color:transparent;-webkit-text-stroke:.5px var(--border);background:0 0;letter-spacing:3px;background:linear-gradient(45deg,#866ee7,#ea60da,#ed8f57,#fbd41d,#2cca91);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;font-weight:800}.btn{display:flex;padding:var(--padding_d2);background:var(--foreground);border:1px solid var(--border);border-radius:var(--radius);gap:var(--padding_d2);cursor:pointer;color:var(--color-nav)}.btn:hover{background:var(--foreground-hover)}html{scroll-behavior:smooth;scroll-padding:2em}body{display:flex;flex-direction:column;height:100%;color:var(--color);background:var(--background);font-family:var(--font-sans)}#content-wrapper{display:flex;flex:1;flex-direction:column;min-height:100svh}#content-wrapper>header{border-bottom:1px solid var(--border)}#content-wrapper>header>a{display:inline-block;padding:var(--padding)}#content-wrapper>footer{display:flex;flex-direction:column;padding:var(--padding)}#content-wrapper>footer>div{display:flex;align-items:center;justify-content:center;padding:var(--padding);gap:var(--padding_d2);text-align:center;flex-wrap:wrap}#content-wrapper>footer>div:first-child{white-space:initial}#content-wrapper>footer>div:first-child a{background:var(--foreground-highlight);color:var(--color-highlight);border-radius:var(--radius);cursor:pointer;padding:0 var(--padding_d2)}#content-wrapper>footer>div:nth-child(2){justify-content:flex-end}main{display:flex;flex:1;flex-direction:column;align-items:center;justify-content:center}main>section{display:flex}main>section>div{display:flex;flex-direction:column}main>section>div>header{display:flex;flex-direction:column;text-align:center;padding:var(--padding_x2)var(--padding);cursor:url("data:image/svg+xml;utf8, πŸ¦„"),auto}main>section>div>header>h1{display:flex;font-size:2.5em;font-weight:800;padding-bottom:calc(var(--padding)*1.2);gap:var(--padding);flex-wrap:wrap;justify-content:center}main>section>div>header>h1>span{color:#866ee7}main>section>div>header>p{color:var(--color-fade);font-size:1.2em}main>section>div>div{display:flex;justify-content:center;gap:var(--padding_x2)}main>section>div>div>.btn{font-size:1.1em;padding:.4em 1em}main>section>div>div>.btn:first-child,main>section>div>div>.btn:first-child:hover{background:var(--foreground-highlight);color:var(--color-highlight)}main>section>div>div>.btn:last-child,main>section>div>div>.btn:last-child:hover{background:var(--foreground-hover)}@media(min-width:1024px){main>section>div>header{padding:var(--padding_x2)var(--padding_x2)calc(var(--padding)*3)}main>section>div>header>h1{font-size:3em}main>section>div>header>p{font-size:1.4em}main>section>div>div{gap:calc(var(--padding)*2.5)}main>section>div>div>.btn{font-size:1.27em}}@media(min-width:1280px){main>section>div>header{padding:var(--padding_x2)calc(var(--padding)*3)calc(var(--padding)*6)}main>section>div>header>h1{font-size:4em}main>section>div>header>p{font-size:1.6em}main>section>div>div{gap:calc(var(--padding)*2.6)}main>section>div>div>.btn{font-size:1.5em}} \ No newline at end of file diff --git a/docs/assets/js/docs.min.12ffdc25c0149ef34e761ee54587f2aae17affcb8375298ad2180851930cb142.js b/docs/assets/js/docs.min.12ffdc25c0149ef34e761ee54587f2aae17affcb8375298ad2180851930cb142.js new file mode 100644 index 0000000..a028e8a --- /dev/null +++ b/docs/assets/js/docs.min.12ffdc25c0149ef34e761ee54587f2aae17affcb8375298ad2180851930cb142.js @@ -0,0 +1 @@ +const lsKeyColorPreference="color-preference",getColorPreference=()=>{let e=localStorage.getItem(lsKeyColorPreference);return e!==null?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"};let colorPreference=getColorPreference();localStorage.setItem(lsKeyColorPreference,colorPreference),document.firstElementChild.setAttribute("data-color",colorPreference);const colorPreferenceButton=document.querySelector("#content-wrapper > footer > div:last-child > button:last-child");colorPreferenceButton&&colorPreferenceButton.addEventListener("click",function(){colorPreference=="dark"?colorPreference="light":colorPreference="dark",setColorPreference()});const setColorPreference=()=>{localStorage.setItem(lsKeyColorPreference,colorPreference),document.firstElementChild.setAttribute("data-color",colorPreference)};window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",({matches:e})=>{colorPreference=e?"dark":"light",setColorPreference()});const body=document.body,bodyModelOuter=document.querySelector("#body-model-outer"),asideWrapper=document.querySelector("#aside-wrapper"),asideWrapperOpenButton=document.querySelector("main > article > nav > button:first-child"),asideWrapperCloseButton=document.querySelector("#aside-wrapper > aside > div .btn");asideWrapper&&asideWrapperOpenButton&&asideWrapperOpenButton.addEventListener("click",function(){body.classList.add("model-open"),bodyModelOuter.style.display="block",asideWrapper.classList.add("open"),asideWrapperCloseButton.addEventListener("click",function(){body.classList.remove("model-open"),bodyModelOuter.style.display="none",asideWrapper.classList.remove("open")}),bodyModelOuter.addEventListener("click",function(){body.classList.remove("model-open"),bodyModelOuter.style.display="none",asideWrapper.classList.remove("open")})});const mainAside=document.querySelector("main > aside"),mainAsideOpenButton=document.querySelector("main > article > nav > button:last-child"),mainAsideCloseButton=document.querySelector("main > aside > div > .btn");mainAside&&mainAsideOpenButton&&mainAsideOpenButton.addEventListener("click",function(){body.classList.add("model-open"),bodyModelOuter.style.display="block",mainAside.classList.add("open"),mainAsideCloseButton.addEventListener("click",function(){body.classList.remove("model-open"),bodyModelOuter.style.display="none",mainAside.classList.remove("open")}),bodyModelOuter.addEventListener("click",function(){body.classList.remove("model-open"),bodyModelOuter.style.display="none",mainAside.classList.remove("open")})}),window.addEventListener("resize",function(){body.classList.contains("model-open")&&(body.classList.remove("model-open"),bodyModelOuter.style.display="none",mainAside.classList.contains("open")&&mainAside.classList.remove("open"),asideWrapper.classList.contains("open")&&asideWrapper.classList.remove("open"))});const asideWrapperSiteLogo=document.querySelector("#aside-wrapper .site-logo"),asideWrapperAsideNav=document.querySelector("#aside-wrapper > aside > nav"),adjustAsideWrapperAsideNavHeight=function(){window.innerWidth>1280?asideWrapperAsideNav.style.height=`${window.innerHeight-1-asideWrapperSiteLogo.getBoundingClientRect().height}px`:asideWrapperAsideNav.style.height=""};adjustAsideWrapperAsideNavHeight(),window.addEventListener("resize",function(){adjustAsideWrapperAsideNavHeight()}),"IntersectionObserver"in window&&document.addEventListener("DOMContentLoaded",function(){const n=document.querySelectorAll("#TableOfContents a");let e=null;const t={},s=new IntersectionObserver(n=>{n.forEach(n=>{n.isIntersecting&&(e&&e.classList.remove("active"),e=t[n.target.id],e&&e.classList.add("active"))})},{rootMargin:`0% 0% -80% 0%`});n.forEach(e=>{const n=e.getAttribute("href")?e.getAttribute("href").slice(1):null;if(n){const o=document.getElementById(n);o&&(t[n]=e,s.observe(o))}e.addEventListener("click",function(){body.classList.contains("model-open")&&mainAsideCloseButton.click()})})}) \ No newline at end of file diff --git a/docs/assets/js/home.min.c8547379013b8a9d3b0bb417291ab4d778359264b06feb44401e3a1a40062184.js b/docs/assets/js/home.min.c8547379013b8a9d3b0bb417291ab4d778359264b06feb44401e3a1a40062184.js new file mode 100644 index 0000000..fc74dea --- /dev/null +++ b/docs/assets/js/home.min.c8547379013b8a9d3b0bb417291ab4d778359264b06feb44401e3a1a40062184.js @@ -0,0 +1 @@ +const lsKeyColorPreference="color-preference",getColorPreference=()=>{let e=localStorage.getItem(lsKeyColorPreference);return e!==null?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"};let colorPreference=getColorPreference();localStorage.setItem(lsKeyColorPreference,colorPreference),document.firstElementChild.setAttribute("data-color",colorPreference);const colorPreferenceButton=document.querySelector("#content-wrapper > footer > div:last-child > button:last-child");colorPreferenceButton&&colorPreferenceButton.addEventListener("click",function(){colorPreference=="dark"?colorPreference="light":colorPreference="dark",setColorPreference()});const setColorPreference=()=>{localStorage.setItem(lsKeyColorPreference,colorPreference),document.firstElementChild.setAttribute("data-color",colorPreference)};window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",({matches:e})=>{colorPreference=e?"dark":"light",setColorPreference()}) \ No newline at end of file diff --git a/docs/categories/index.xml b/docs/categories/index.xml new file mode 100644 index 0000000..c59a04b --- /dev/null +++ b/docs/categories/index.xml @@ -0,0 +1 @@ +Categories on Learning Rusthttps://learning-rust.github.io/categories/Recent content in Categories on Learning RustHugoen-US \ No newline at end of file diff --git a/docs/docs/borrowing/index.html b/docs/docs/borrowing/index.html new file mode 100644 index 0000000..0e3ccc5 --- /dev/null +++ b/docs/docs/borrowing/index.html @@ -0,0 +1,79 @@ +Borrowing Β· Learning Rust +

Borrowing

In real life applications, most of the times we have to pass variable bindings to other functions or assign them to other variable bindings. In this case, we are referencing the original binding; borrow the data of it.

What is Borrowing?

Borrow (verb)
To receive something with the promise of returning it.

Shared & Mutable borrowings

⭐️ There are two types of Borrowing,

  1. Shared Borrowing (&T)

    • A piece of data can be borrowed by a single or multiple users, but data should not be altered.
  2. Mutable Borrowing (&mut T)

    • A piece of data can be borrowed and altered by a single user, but the data should not be accessible for any other users at that time.

Rules for borrowings

There are very important rules regarding borrowing,

  1. One piece of data can be borrowed either as a shared borrow or as a mutable borrow at a given time. But not both at the same time.

  2. Borrowing applies for both copy types and move types.

  3. The concept of Liveness ↴

fn main() {
+  let mut a = vec![1, 2, 3];
+  let b = &mut a;  //  &mut borrow of `a` starts here
+                   //  ⁝
+  // some code     //  ⁝
+  // some code     //  ⁝
+}                  //  &mut borrow of `a` ends here
+
+
+fn main() {
+  let mut a = vec![1, 2, 3];
+  let b = &mut a;  //  &mut borrow of `a` starts here
+  // some code
+
+  println!("{:?}", a); // trying to access `a` as a shared borrow, so giving an error
+}                  //  &mut borrow of `a` ends here
+
+
+fn main() {
+  let mut a = vec![1, 2, 3];
+  {
+    let b = &mut a;  //  &mut borrow of `a` starts here
+    // any other code
+  }                  //  &mut borrow of `a` ends here
+
+  println!("{:?}", a); // allow borrowing `a` as a shared borrow
+}
+

πŸ’‘ Let’s see how to use shared and mutable borrowings in examples.

Examples for Shared Borrowing

fn main() {
+    let a = [1, 2, 3];
+    let b = &a;
+    println!("{:?} {}", a, b[0]); // [1, 2, 3] 1
+}
+
+
+fn main() {
+    let a = vec![1, 2, 3];
+    let b = get_first_element(&a);
+
+    println!("{:?} {}", a, b); // [1, 2, 3] 1
+}
+
+fn get_first_element(a: &Vec<i32>) -> i32 {
+    a[0]
+}
+

Examples for Mutable Borrowing

fn main() {
+    let mut a = [1, 2, 3];
+    let b = &mut a;
+    b[0] = 4;
+    println!("{:?}", b); // [4, 2, 3]
+}
+
+
+fn main() {
+    let mut a = [1, 2, 3];
+    {
+        let b = &mut a;
+        b[0] = 4;
+    }
+
+    println!("{:?}", a); // [4, 2, 3]
+}
+
+
+fn main() {
+    let mut a = vec![1, 2, 3];
+    let b = change_and_get_first_element(&mut a);
+
+    println!("{:?} {}", a, b); // [4, 2, 3] 4
+}
+
+fn change_and_get_first_element(a: &mut Vec<i32>) -> i32 {
+    a[0] = 4;
+    a[0]
+}
+
\ No newline at end of file diff --git a/docs/docs/cargo-crates-and-basic-project-structure/index.html b/docs/docs/cargo-crates-and-basic-project-structure/index.html new file mode 100644 index 0000000..f16c8c2 --- /dev/null +++ b/docs/docs/cargo-crates-and-basic-project-structure/index.html @@ -0,0 +1,36 @@ +Cargo, Crates and Basic Project Structure Β· Learning Rust +

Cargo, Crates and Basic Project Structure

Cargo

Cargo is Rust’s built-in package manager and build system. It also supports the following actions,

CommandAction
cargo newCreate a new project
cargo initCreate a new project in an existing directory
cargo checkVerify the project compiles without errors
cargo buildBuild the executable
cargo runBuild the executable and run

πŸ’‘ The cargo check command verifies that the project compiles without errors, without producing an executable. +Thus, it is often faster than cargo build.

πŸ’‘ Cargo places executables compiled with cargo build or cargo run in the target/debug/ directory. +But, while those built with cargo build --release for release purposes are stored in target/release/ directory. +Release builds use more optimizations and remove some runtime safety checks to increase performance, although this comes at the cost of longer compile time.

CommandAction
cargo addAdd a dependency crate to the project
cargo removeRemove a dependency crate from the project
cargo fetchDownload the dependencies specified in Cargo.lock
cargo updateUpdate project dependencies

πŸ’‘ A crate is a package that can be shared via crates.io, Rust community’s crate registry. +cargo add, cargo remove, cargo fetch, and cargo update commands manage project dependencies through the crate hosted on crates.io.

πŸ’‘ The cargo add command includes a specified crate in the [dependencies] section of Cargo.toml, while cargo add --dev adds a crate to the [dev-dependencies] section. This indicates that the crate is only used for development purposes like testing and will not be included in the final compiled code.

CommandAction
cargo testRun tests
cargo benchRun benchmarks
cargo docGenerate the project documentation via rustdoc

In addition, there are cargo commands to publish the project as a crate to crates.io.

CommandAction
cargo loginLogin to crates.io with the API token
cargo packageMake the local crate uploadable to crates.io
cargo publishUpload the crate to crates.io
cargo installInstall a Rust binary
cargo uninstallUninstall a Rust binary

πŸ’‘ You need to get an API token from crates.io to publish a crate to it. The API token can be found in the Account Settings page, after login to that site. We will discuss more about this under code organization with crates.

Crate

  • A crate is a package, which can be shared via Rust community’s crate registry, crates.io.

  • A crate can produce an executable or a library. In other words, it can be a binary crate or a library crate.

    1. cargo new crate_name --bin or cargo new crate_name: Produces an executable
    2. cargo new crate_name --lib: Produces a library

The first one generates,

β”œβ”€β”€ Cargo.toml
+└── src
+    └── main.rs
+

and the second one generates,

β”œβ”€β”€ Cargo.toml
+└── src
+    └── lib.rs
+
  • Cargo.toml(capital c) is the configuration file which contains all of the metadata that Cargo needs to compile your project.
  • src folder is the place to store the source code.
  • Each crate has an implicit crate root/ entry point. main.rs is the crate root for a binary crate and lib.rs is the crate root for a library crate.

Project Structure

This is how Cargo documentation describes about the recommended project layout,

.
+β”œβ”€β”€ Cargo.toml
+β”œβ”€β”€ Cargo.lock
+β”œβ”€β”€ src
+β”‚   β”œβ”€β”€ main.rs
+β”‚   β”œβ”€β”€ lib.rs
+β”‚   └── bin
+β”‚       β”œβ”€β”€ another_executable.rs
+β”‚       └── multi_file_executable
+β”‚           β”œβ”€β”€ main.rs
+β”‚           └── some_module.rs
+β”œβ”€β”€ tests
+β”‚   └── some_integration_tests.rs
+β”œβ”€β”€ benches
+β”‚   └── simple_bench.rs
+└── examples
+    └── simple_example.rs
+
  • The source code goes in the src directory.
    • The default executable file is src/main.rs.
    • The default library file is src/lib.rs.
    • Other executables can be placed in,
      • src/bin/*.rs
      • src/bin/*/main.rs
  • Integration tests go in the tests directory (unit tests go in each file they’re testing).
  • Benchmarks go in the benches directory.
  • Examples go in the examples directory.

Rust Editions

Rust guarantees backward compatibility while introducing major updates to the language. To support this, the edition field was added to the Cargo.toml file in Rust 2018, marking the first major update to the language ecosystem three years after its initial release. Editions are opt-in, meaning existing crates will not experience these changes until they explicitly migrate to the new edition.

The major editions of Rust are:

  • Rust 2015: The initial edition, introduced with Rust 1.0. It established the core language features like ownership, borrowing, and lifetimes, laying the foundation for Rust’s safety and concurrency guarantees.

  • Rust 2018: The first major update, introduced the edition field in Cargo.toml, simplified the module system, stabilized async/await, improved error handling with the ? operator, and made several syntactic changes.

  • Rust 2021: Focused on improving ergonomics and removing inconsistencies, such as disjoint closure capture, IntoIterator for arrays, and the introduction of or-patterns in macros.

  • Rust 2024: The latest edition, includes enhancements like refined async features, more const generics, better diagnostics, and improved Cargo features.

For new projects created by cargo new, it will set edition = "2024" by default in the Cargo.toml file. For example,

[package]
+name = "hello_world"
+version = "0.1.0"
+edition = "2024"
+

πŸ‘¨β€πŸ« Before going to the next…

  • The .cargo/bin directory of your home directory is the default location of Rust binaries. Not only the official binaries like rustc, cargo, rustup, rustfmt, rustdoc, rust-analyzer and also the binaries you can install via cargo install command, will be stored in this directory.

  • Even though the initial convention for naming crates and file names is using the snake_case, some crate developers are using kebab-case on both crates and file names. To make your code more consistent, use the initial convention snake_case; especially on file names.

  • Create an executable crate via cargo new command and run it via cargo run.

  • Create a library crate via cargo new command and run cargo test.

\ No newline at end of file diff --git a/docs/docs/code-organization/index.html b/docs/docs/code-organization/index.html new file mode 100644 index 0000000..ccb5830 --- /dev/null +++ b/docs/docs/code-organization/index.html @@ -0,0 +1,5 @@ +Code Organization Β· Learning Rust +

Code Organization

When a single code block is getting larger, it should be decomposed into smaller pieces and should be organized in a proper manner. Rust supports different levels of code organization.

1. Functions

2. Modules

Can be mapped to a,

  • Inline module
  • File
  • Directory hierarchy

3. Crates

Can be mapped to a,

  • lib.rs file on the same executable crate

  • Dependency crate specified on Cargo.toml

    Can be specified from,

    • Path
    • Git repository
    • crates.io

4. Workspaces

Helps to manage multiple crates as a single project.

Let’s discuss one by one.

πŸ’‘ To make examples more simpler, we use a simple function which prints β€œHello, world!”. But regarding writing testable codes, always try to return the String from the function and print it when calling it, instead of printing the String inside the function.

\ No newline at end of file diff --git a/docs/docs/combinators/index.html b/docs/docs/combinators/index.html new file mode 100644 index 0000000..c656c28 --- /dev/null +++ b/docs/docs/combinators/index.html @@ -0,0 +1,189 @@ +Combinators Β· Learning Rust +

Combinators

What is a combinator?

  • One meaning of β€œcombinator” is a more informal sense referring to the combinator pattern, a style of organizing libraries centered around the idea of combining things. Usually there is some type T, some functions for constructing β€œprimitive” values of type T, and some β€œcombinators” which can combine values of type T in various ways to build up more complex values of type T. The other definition is “function with no free variables”. +__ wiki.haskell.org

  • A combinator is a function which builds program fragments from program fragments; in a sense the programmer using combinators constructs much of the desired program automatically, rather that writing every detail by hand. +__ John Hughesβ€”Generalizing Monads to Arrows via Functional Programming Concepts

The exact definition of “combinators” in Rust ecosystem is bit unclear.Β 

  • or(), and(), or_else(), and_then()

    • Combine two values of type T and return same type T.
  • filter() for Option types

    • Filter type T by using a closure as a conditional function
    • Return same type T
  • map(), map_err()

    • Convert type T by applying a closure.
    • The data type of the value inside T can be changed. +ex. Some<&str> can be converted to Some<usize> or Err<&str> to Err<isize> and etc.
  • map_or(), map_or_else()

    • Transform type T by applying a closure & return the value inside type T.
    • For None and Err, a default value or another closure is applied.
  • ok_or(), ok_or_else() for Option types

    • Transform Option type into a Result type.
  • as_ref(), as_mut()

    • Transform type T into a reference or a mutable reference.

or() and and()

While combining two expressions, which return either Option/ Result

  • or(): If either one got Some or Ok, that value returns immediately.
  • and(): If both got Some or Ok, the value in the second expression returns. If either one got None or Err that value returns immediately.
fn main() {
+  let s1 = Some("some1");
+  let s2 = Some("some2");
+  let n: Option<&str> = None;
+
+  let o1: Result<&str, &str> = Ok("ok1");
+  let o2: Result<&str, &str> = Ok("ok2");
+  let e1: Result<&str, &str> = Err("error1");
+  let e2: Result<&str, &str> = Err("error2");
+
+  assert_eq!(s1.or(s2), s1); // Some1 or Some2 = Some1
+  assert_eq!(s1.or(n), s1);  // Some or None = Some
+  assert_eq!(n.or(s1), s1);  // None or Some = Some
+  assert_eq!(n.or(n), n);    // None1 or None2 = None2
+
+  assert_eq!(o1.or(o2), o1); // Ok1 or Ok2 = Ok1
+  assert_eq!(o1.or(e1), o1); // Ok or Err = Ok
+  assert_eq!(e1.or(o1), o1); // Err or Ok = Ok
+  assert_eq!(e1.or(e2), e2); // Err1 or Err2 = Err2
+
+  assert_eq!(s1.and(s2), s2); // Some1 and Some2 = Some2
+  assert_eq!(s1.and(n), n);   // Some and None = None
+  assert_eq!(n.and(s1), n);   // None and Some = None
+  assert_eq!(n.and(n), n);    // None1 and None2 = None1
+  
+  assert_eq!(o1.and(o2), o2); // Ok1 and Ok2 = Ok2
+  assert_eq!(o1.and(e1), e1); // Ok and Err = Err
+  assert_eq!(e1.and(o1), e1); // Err and Ok = Err
+  assert_eq!(e1.and(e2), e1); // Err1 and Err2 = Err1
+}
+

πŸ”Ž Rust nightly support xor() for Option types, which returns Some only if one expression got Some, but not both.

or_else()

Similar to or(). The only difference is, the second expression should be a closure which returns same type T.

fn main() {
+    // or_else with Option
+    let s1 = Some("some1");
+    let s2 = Some("some2");
+    let fn_some = || Some("some2"); // similar to: let fn_some = || -> Option<&str> { Some("some2") };
+
+    let n: Option<&str> = None;
+    let fn_none = || None;
+
+    assert_eq!(s1.or_else(fn_some), s1);  // Some1 or_else Some2 = Some1
+    assert_eq!(s1.or_else(fn_none), s1);  // Some or_else None = Some
+    assert_eq!(n.or_else(fn_some), s2);   // None or_else Some = Some
+    assert_eq!(n.or_else(fn_none), None); // None1 or_else None2 = None2
+
+    // or_else with Result
+    let o1: Result<&str, &str> = Ok("ok1");
+    let o2: Result<&str, &str> = Ok("ok2");
+    let fn_ok = |_| Ok("ok2"); // similar to: let fn_ok = |_| -> Result<&str, &str> { Ok("ok2") };
+
+    let e1: Result<&str, &str> = Err("error1");
+    let e2: Result<&str, &str> = Err("error2");
+    let fn_err = |_| Err("error2");
+
+    assert_eq!(o1.or_else(fn_ok), o1);  // Ok1 or_else Ok2 = Ok1
+    assert_eq!(o1.or_else(fn_err), o1); // Ok or_else Err = Ok
+    assert_eq!(e1.or_else(fn_ok), o2);  // Err or_else Ok = Ok
+    assert_eq!(e1.or_else(fn_err), e2); // Err1 or_else Err2 = Err2
+}
+

and_then()

Similar to and(). The only difference is, the second expression should be a closure which returns same type T.

fn main() {
+    // and_then with Option
+    let s1 = Some("some1");
+    let s2 = Some("some2");
+    let fn_some = |_| Some("some2"); // similar to: let fn_some = |_| -> Option<&str> { Some("some2") };
+
+    let n: Option<&str> = None;
+    let fn_none = |_| None;
+
+    assert_eq!(s1.and_then(fn_some), s2); // Some1 and_then Some2 = Some2
+    assert_eq!(s1.and_then(fn_none), n);  // Some and_then None = None
+    assert_eq!(n.and_then(fn_some), n);   // None and_then Some = None
+    assert_eq!(n.and_then(fn_none), n);   // None1 and_then None2 = None1
+
+    // and_then with Result
+    let o1: Result<&str, &str> = Ok("ok1");
+    let o2: Result<&str, &str> = Ok("ok2");
+    let fn_ok = |_| Ok("ok2"); // similar to: let fn_ok = |_| -> Result<&str, &str> { Ok("ok2") };
+
+    let e1: Result<&str, &str> = Err("error1");
+    let e2: Result<&str, &str> = Err("error2");
+    let fn_err = |_| Err("error2");
+
+    assert_eq!(o1.and_then(fn_ok), o2);  // Ok1 and_then Ok2 = Ok2
+    assert_eq!(o1.and_then(fn_err), e2); // Ok and_then Err = Err
+    assert_eq!(e1.and_then(fn_ok), e1);  // Err and_then Ok = Err
+    assert_eq!(e1.and_then(fn_err), e1); // Err1 and_then Err2 = Err1
+}
+

filter()

πŸ’‘ Usually in programming languages filter functions are used with arrays or iterators to create a new array/ iterator by filtering own elements via a function/ closure. Rust also provides filter() as an iterator adaptor to apply a closure on each element of an iterator to transform it into another iterator. However in here we are talking about the functionality of filter() with Option types.

The same Some type is returned, only if we pass a Some value and the given closure returned true for it. None is returned, if None type passed or the closure returned false. The closure uses the value inside Some as an argument. Still Rust support filter() only for Option types.

fn main() {
+    let s1 = Some(3);
+    let s2 = Some(6);
+    let n = None;
+
+    let fn_is_even = |x: &i8| x % 2 == 0;
+
+    assert_eq!(s1.filter(fn_is_even), n);  // Some(3) -> 3 is not even -> None
+    assert_eq!(s2.filter(fn_is_even), s2); // Some(6) -> 6 is even -> Some(6)
+    assert_eq!(n.filter(fn_is_even), n);   // None -> no value -> None
+}
+

map() and map_err()

πŸ’‘ Usually in programming languages map() functions are used with arrays or iterators, to apply a closure on each element of the array or iterator. Rust also provides map() as an iterator adaptor to apply a closure on each element of an iterator to transform it into another iterator. However in here we are talking about the functionality of map() with Option and Result types.

  • map() : Convert type T by applying a closure. The data type of Some or Ok blocks can be changed according to the return type of the closure. Convert Option<T> to Option<U>, Result<T, E> to Result<U, E>

⭐ Via map(), only Some and Ok values are getting changed. No affect to the values inside Err (None doesn’t contain any value at all).

fn main() {
+    let s1 = Some("abcde");
+    let s2 = Some(5);
+
+    let n1: Option<&str> = None;
+    let n2: Option<usize> = None;
+
+    let o1: Result<&str, &str> = Ok("abcde");
+    let o2: Result<usize, &str> = Ok(5);
+    
+    let e1: Result<&str, &str> = Err("abcde");
+    let e2: Result<usize, &str> = Err("abcde");
+    
+    let fn_character_count = |s: &str| s.chars().count();
+
+    assert_eq!(s1.map(fn_character_count), s2); // Some1 map = Some2
+    assert_eq!(n1.map(fn_character_count), n2); // None1 map = None2
+
+    assert_eq!(o1.map(fn_character_count), o2); // Ok1 map = Ok2
+    assert_eq!(e1.map(fn_character_count), e2); // Err1 map = Err2
+}
+
  • map_err() for Result types : The data type of Err blocks can be changed according to the return type of the closure. Convert Result<T, E> to Result<T, F>.

⭐ Via map_err(), only Err values are getting changed. No affect to the values inside Ok.

fn main() {
+    let o1: Result<&str, &str> = Ok("abcde");
+    let o2: Result<&str, isize> = Ok("abcde");
+
+    let e1: Result<&str, &str> = Err("404");
+    let e2: Result<&str, isize> = Err(404);
+
+    let fn_character_count = |s: &str| -> isize { s.parse().unwrap() }; // convert str to isize
+
+    assert_eq!(o1.map_err(fn_character_count), o2); // Ok1 map = Ok2
+    assert_eq!(e1.map_err(fn_character_count), e2); // Err1 map = Err2
+}
+

map_or() and map_or_else()

Hope you remember the functionality of unwrap_or() and unwrap_or_else() functions. These functions also bit similar to them. But map_or() and map_or_else() apply a closure on Some and Ok values and return the value inside type T.

  • map_or() : Support only for Option types (not supporting Result). Apply the closure to the value inside Some and return the output according to the closure. The given default value is returned for None types.
fn main() {
+    const V_DEFAULT: i8 = 1;
+    
+    let s = Some(10);
+    let n: Option<i8> = None;
+    let fn_closure = |v: i8| v + 2;
+
+    assert_eq!(s.map_or(V_DEFAULT, fn_closure), 12);
+    assert_eq!(n.map_or(V_DEFAULT, fn_closure), V_DEFAULT);
+}
+
  • map_or_else() : Support for both Option and Result types (Result still nightly only). Similar to map_or() but should provide another closure instead a default value for the first parameter.

⭐ None types doesn’t contain any value. So no need to pass anything to the closure as input with Option types. But Err types contain some value inside it. So default closure should able to read it as an input, while using this with Result types.

#![feature(result_map_or_else)] // enable unstable library feature 'result_map_or_else' on nightly
+fn main() {
+    let s = Some(10);
+    let n: Option<i8> = None;
+
+    let fn_closure = |v: i8| v + 2;
+    let fn_default = || 1; // None doesn't contain any value. So no need to pass anything to closure as input.
+
+    assert_eq!(s.map_or_else(fn_default, fn_closure), 12);
+    assert_eq!(n.map_or_else(fn_default, fn_closure), 1);
+
+    let o = Ok(10);
+    let e = Err(5);
+    let fn_default_for_result = |v: i8| v + 1; // Err contain some value inside it. So default closure should able to read it as input
+
+    assert_eq!(o.map_or_else(fn_default_for_result, fn_closure), 12);
+    assert_eq!(e.map_or_else(fn_default_for_result, fn_closure), 6);
+}
+

ok_or() and ok_or_else()

As mentioned earlier, ok_or(), ok_or_else() transform Option type into Result type. Some to Ok and None to Err.

  • ok_or() : A default Err message should pass as argument.
fn main() {
+    const ERR_DEFAULT: &str = "error message";
+
+    let s = Some("abcde");
+    let n: Option<&str> = None;
+
+    let o: Result<&str, &str> = Ok("abcde");
+    let e: Result<&str, &str> = Err(ERR_DEFAULT);
+
+    assert_eq!(s.ok_or(ERR_DEFAULT), o); // Some(T) -> Ok(T)
+    assert_eq!(n.ok_or(ERR_DEFAULT), e); // None -> Err(default)
+}
+
  • ok_or_else() : Similar to ok_or(). A closure should be passed as the argument.
fn main() {
+    let s = Some("abcde");
+    let n: Option<&str> = None;
+    let fn_err_message = || "error message";
+
+    let o: Result<&str, &str> = Ok("abcde");
+    let e: Result<&str, &str> = Err("error message");
+
+    assert_eq!(s.ok_or_else(fn_err_message), o); // Some(T) -> Ok(T)
+    assert_eq!(n.ok_or_else(fn_err_message), e); // None -> Err(default)
+}
+

as_ref() and as_mut()

πŸ”Ž As mentioned earlier, these functions are used to borrow type T as a reference or as a mutable reference.

  • as_ref() : Convert Option<T> to Option<&T> and Result<T, E> to Result<&T, &E>
  • as_mut() : Converts Option<T> to Option<&mut T> and Result<T, E> to Result<&mut T, &mut E>
\ No newline at end of file diff --git a/docs/docs/comments-and-documenting-the-code/index.html b/docs/docs/comments-and-documenting-the-code/index.html new file mode 100644 index 0000000..b061ed6 --- /dev/null +++ b/docs/docs/comments-and-documenting-the-code/index.html @@ -0,0 +1,42 @@ +Comments and Documenting the code Β· Learning Rust +

Comments and Documenting the code

Comments

// Line comments
+/* Block comments */
+

Nested block comments are supported.

πŸ’‘ By convention, try to avoid using block comments. Use line comments instead.

Doc Comments

As we discussed, we can generate the project documentation via rustdoc by running the cargo doc command. It uses the doc comments to generate the documentation.

πŸ’‘ Usually we are adding doc comments on library crates. Also, we can use Markdown notations inside the doc comments.

/// Line comments; document the next item
+/** Block comments; document the next item */
+
+//! Line comments; document the enclosing item
+/*! Block comments; document the enclosing item !*/
+

For example,

/// This module contains tests; Outer comment
+mod tests {
+    
+}
+
+mod tests {
+    //! This module contains tests; Inner comment
+
+}
+

πŸ’­ The mod keyword is used for modules. Don’t worry about this for now; it’ll be discussed later.

Doc Attributes

Doc attributes are alternatives for doc comments. Especially, we use these doc attributes while we need to set controls on rustdoc. Refer the doc attributes section of rustdoc documentation for more details.

In the following example, each comment is equivalent to relevant doc attribute.

/// Outer comment
+#[doc = "Outer comment"]
+
+//! Inner comment
+#![doc = "Inner comment"]
+

πŸ”Ž An attribute is a general, free-form metadatum that is interpreted according to the name, convention, language and compiler version. Any item declaration may have an attribute applied to it. Syntax:

  • Outer attribute: #[attr]
  • Inner attribute: #![attr]

πŸ‘¨β€πŸ« Before going to the next…

  • Use //! only to write crate-level documentation, nothing else. When using mod blocks, use /// outside of the block. Check the usage of //! and /// doc comments of few popular crates on crates.io. For example, check serde/src/lib.rs and rand/src/lib.rs.

  • Run cargo new hello_lib --lib command to create a sample crate and replace its src/lib.rs file with the following code. Then run cd hello_lib && cargo doc --open to generate the documentation and open it from your web browser.

//! A Simple Hello World Crate
+
+/// This function returns the greeting; Hello, world!
+pub fn hello() -> String {
+	("Hello, world!").to_string()
+}
+
+#[cfg(test)]
+mod tests {
+    use super::hello;
+
+    #[test]
+    fn test_hello() {
+        assert_eq!(hello(), "Hello, world!");
+    }
+}
+
\ No newline at end of file diff --git a/docs/docs/control-flows/index.html b/docs/docs/control-flows/index.html new file mode 100644 index 0000000..c11b8c5 --- /dev/null +++ b/docs/docs/control-flows/index.html @@ -0,0 +1,202 @@ +Control Flows Β· Learning Rust +

Control Flows

if - else if - else

  • Using only if block.
let age = 13;
+
+if age < 18 {
+    println!("Hello, child!"); // The code prints this
+}
+
  • Using only if and else blocks.
let i = 7;
+
+if i % 2 == 0 {
+    println!("Even");
+} else {
+    println!("Odd"); // The code prints this
+}
+
  • Using with let statement.
let age: u8 = 13;
+let is_below_eighteen = if age < 18 { true } else { false }; // true
+
  • More examples,
// i. A simple example
+let team_size = 7;
+
+if team_size < 5 {
+    println!("Small");
+} else if team_size < 10 {
+    println!("Medium"); // The code prints this
+} else {
+    println!("Large");
+}
+
// ii. Let's refactor above code
+let team_size = 7;
+let team_size_in_text;
+
+if team_size < 5 {
+    team_size_in_text = "Small";
+} else if team_size < 10 {
+    team_size_in_text = "Medium";
+} else {
+    team_size_in_text = "Large";
+}
+
+println!("Current team size : {}", team_size_in_text); // Current team size : Medium
+
// iii. Let's refactor further
+let team_size = 7;
+let team_size = if team_size < 5 {
+    "Small" // ⭐️ no ;
+} else if team_size < 10 {
+    "Medium"
+} else {
+    "Large"
+};
+
+println!("Current team size : {}", team_size); // Current team size : Medium
+

⭐️ Return data type should be the same on each block when using this as an expression.

match

let tshirt_width = 20;
+let tshirt_size = match tshirt_width {
+    16 => "S", // check 16
+    17 | 18 => "M", // check 17 and 18
+    19 ..= 21 => "L", // check from 19 to 21 (19,20,21)
+    22 => "XL",
+    _ => "Not Available",
+};
+
+println!("{}", tshirt_size); // L
+
let is_allowed = false;
+let list_type = match is_allowed {
+    true => "Full",
+    false => "Restricted"
+    // no default/ _ condition can be skipped
+    // Because data type of is_allowed is boolean and all possibilities checked on conditions
+};
+
+println!("{}", list_type); // Restricted
+
let marks_paper_a: u8 = 25;
+let marks_paper_b: u8 = 30;
+
+let output = match (marks_paper_a, marks_paper_b) {
+    (50, 50) => "Full marks for both papers",
+    (50, _) => "Full marks for paper A",
+    (_, 50) => "Full marks for paper B",
+    (x, y) if x > 25 && y > 25 => "Good",
+    (_, _) => "Work hard"
+};
+
+println!("{}", output); // Work hard
+

loop

loop {
+	println!("Loop forever!");
+}
+
// Usage of break and continue
+let mut a = 0;
+
+loop {
+	if a == 0 {
+		println!("Skip Value : {}", a);
+		a += 1;
+		continue;
+	} else if a == 2 {
+		println!("Break At : {}", a);
+		break;
+	}
+
+	println!("Current Value : {}", a);
+	a += 1;
+}
+
// Outer break
+let mut b1 = 1;
+
+'outer_loop: loop { //set label outer_loop
+  let mut b2 = 1;
+
+  'inner_loop: loop {
+    println!("Current Value : [{}][{}]", b1, b2);
+
+    if b1 == 2 && b2 == 2 {
+        break 'outer_loop; // kill outer_loop
+    } else if b2 == 5 {
+    	break;
+    }
+
+    b2 += 1;
+  }
+
+  b1 += 1;
+}
+

while

let mut a = 1;
+
+while a <= 10 {
+	println!("Current value : {}", a);
+	a += 1; //no ++ or -- on Rust
+}
+
// Usage of break and continue
+let mut b = 0;
+
+while b < 5 {
+	if b == 0 {
+		println!("Skip value : {}", b);
+		b += 1;
+		continue;
+	} else if b == 2 {
+		println!("Break At : {}", b);
+		break;
+	}
+
+	println!("Current value : {}", b);
+	b += 1;
+}
+
// Outer break
+let mut c1 = 1;
+
+'outer_while: while c1 < 6 { //set label outer_while
+	let mut c2 = 1;
+
+	'inner_while: while c2 < 6 {
+		println!("Current Value : [{}][{}]", c1, c2);
+		if c1 == 2 && c2 == 2 { break 'outer_while; } //kill outer_while
+		c2 += 1;
+	}
+
+	c1 += 1;
+}
+

for

// 0 to 10 (10 exclusive); In other languages, `for(i = 0; i < 10; i++)`
+for i in 0..10 {
+  println!("Current value : {}", i);
+}
+
// 1 to 10 (10 inclusive); In other languages, `for(i = 1; i <= 10; i++)`
+for i in 1..=10 {
+  println!("Current value : {}", i);
+}
+
// Usage of break and continue
+for b in 0..6 {
+  if b == 0 {
+    println!("Skip Value : {}", b);
+    continue;
+  } else if b == 2 {
+    println!("Break At : {}", b);
+    break;
+  }
+
+  println!("Current value : {}", b);
+}
+
// Outer break
+'outer_for: for c1 in 1..6 { //set label outer_for
+
+  'inner_for: for c2 in 1..6 {
+    println!("Current Value : [{}][{}]", c1, c2);
+    if c1 == 2 && c2 == 2 { break 'outer_for; } //kill outer_for
+  }
+
+}
+
// Working with arrays/vectors
+let group : [&str; 4] = ["Mark", "Larry", "Bill", "Steve"];
+
+for n in 0..group.len() { // group.len() = 4 -> 0..4 πŸ‘Ž check group.len() on each iteration
+  println!("Current Person : {}", group[n]);
+}
+
+for person in group.iter() { // πŸ‘ group.iter() turn the array into a simple iterator
+  println!("Current Person : {}", person);
+}
+
+for (index, person) in group.iter().enumerate() { // πŸ’‘ group.iter().enumerate() helps to read both the current index (starting from zero) and the value
+  println!("Person {} : {}", index, person);
+}
+
\ No newline at end of file diff --git a/docs/docs/crates/index.html b/docs/docs/crates/index.html new file mode 100644 index 0000000..30b47b1 --- /dev/null +++ b/docs/docs/crates/index.html @@ -0,0 +1,201 @@ +Crates Β· Learning Rust +

Crates

πŸ’­ Crates are a bit similar to the packages in some other languages. Crates compile individually. If the crate has child file modules, those files will get merged with the crate file and compile as a single unit.

πŸ’­ A crate can produce an executable/ a binary or a library. src/main.rs is the crate root/ entry point for a binary crate and src/lib.rs is the entry point for a library crate.

01. lib.rs on executable crate

πŸ’‘ When writing binary crates, we can move the main functionalities to src/lib.rs and use it as a library from src/main.rs. This pattern is quite common on executable crates.

// # Think we run,
+cargo new greetings
+touch greetings/src/lib.rs
+
+// # It generates,
+greetings
+ β”œβ”€β”€ Cargo.toml
+ └── src
+    β”œβ”€β”€ lib.rs
+    └── main.rs
+
+// # Think we modify following files,
+
+// 01. greetings/src/lib.rs
+pub fn hello() {
+    println!("Hello, world!");
+}
+
+// 02. greetings/src/main.rs
+extern crate greetings;
+
+fn main() {
+    greetings::hello();
+}
+

πŸ’― As I mentioned earlier, in here we use simplest examples to reduce the complexity of learning materials. But this is how we need to write greetings/src/lib.rs to make the code more testable.

// greetings/src/lib.rs
+pub fn hello() -> String {
+  //! This returns `Hello, world!` String
+  ("Hello, world!").to_string()
+}
+
+// 01. Tests for `hello()`
+#[test] // Indicates that this is a test function
+fn test_hello() {
+  assert_eq!(hello(), "Hello, world!");
+}
+
+// 02. Tests for `hello()`, Idiomatic way
+#[cfg(test)] // Only compiles when running tests
+mod tests { // Separates tests from code
+  use super::hello; // Import root `hello()` function
+  
+    #[test]
+    fn test_hello() {
+        assert_eq!(hello(), "Hello, world!");
+    }
+}
+

πŸ“– When importing a crate that has dashes in its name β€œlike-this”, which is not a valid Rust identifier, it will be converted by changing the dashes to underscores, so you would write extern crate like_this;

lib.rs can link with multiple files.

// # Think we run,
+cargo new phrases
+touch phrases/src/lib.rs
+touch phrases/src/greetings.rs
+
+// # It generates,
+phrases
+ β”œβ”€β”€ Cargo.toml
+ └── src
+    β”œβ”€β”€ greetings.rs
+    β”œβ”€β”€ lib.rs
+    └── main.rs
+   
+// # Think we modify following files,
+
+// 01. phrases/src/greetings.rs
+pub fn hello() {
+    println!("Hello, world!");
+}
+
+// 02. phrases/src/main.rs
+extern crate phrases;
+
+fn main() {
+    phrases::greetings::hello();
+}
+
+// 03. phrases/src/lib.rs
+pub mod greetings; // ⭐️ Import `greetings` module as a public module
+

02. Dependency crate on Cargo.toml

When the code in the lib.rs file is getting larger, we can move those into a separate library crate and use it as a dependency of the main crate. As we mentioned earlier, a dependency can be specified from a folder path, git repository or by crates.io.

a. Using folder path

Let’s see how to create a nested crate and use it as a dependency using folder path,

// # Think we run,
+cargo new phrases
+cargo new phrases/greetings --lib
+
+// # It generates,
+phrases
+ β”œβ”€β”€ Cargo.toml
+ β”œβ”€β”€ greetings
+ β”‚  β”œβ”€β”€ Cargo.toml
+ β”‚  └── src
+ β”‚     └── lib.rs
+ └── src
+    └── main.rs
+
+// # Think we modify following files,
+
+// 01. phrases/Cargo.toml
+[package]
+name = "phrases"
+version = "0.1.0"
+authors = ["Dumindu Madunuwan"]
+
+[dependencies]
+greetings = { path = "greetings" }
+
+// 02. phrases/greetings/src/lib.rs
+pub fn hello() {
+    println!("Hello, world!");
+}
+
+// 03. phrases/src/main.rs
+extern crate greetings;
+
+fn main() {
+    greetings::hello();
+}
+

b. Using git repository

If you want to use a library crate on multiple projects, one way is moving crate code to a git repository and use it as a dependency when needed.

// -- Cargo.toml --
+[dependencies]
+
+// 01. Get the latest commit on the master branch
+rocket = { git = "https://github.com/SergioBenitez/Rocket" }
+
+// 02. Get the latest commit of a specific branch
+rocket = { git = "https://github.com/SergioBenitez/Rocket", branch = "v0.3" }
+
+// 03. Get a specific tag
+rocket = { git = "https://github.com/SergioBenitez/Rocket", tag = "v0.3.2" }
+
+// 04. Get a specific revision (on master or any branch, according to rev)
+rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "8183f636305cef4adaa9525506c33cbea72d1745" }
+

c. Using crates.io

The other way is uploading it to crates.io and use it as a dependency when needed.

🚧 First, let’s create a simple β€œHello world” crate and upload it to crates.io.

// # Think we run,
+cargo new test_crate_hello_world --lib
+
+// # It generates,
+test_crate_hello_world
+ β”œβ”€β”€ Cargo.toml
+ └── src
+    └── lib.rs
+   
+// # Think we modify following files,
+
+// 01. test_crate_hello_world/Cargo.toml
+[package]
+name = "test_crate_hello_world"
+version = "0.1.0"
+authors = ["Dumindu Madunuwan"]
+
+description = "A Simple Hello World Crate"
+repository = "https://github.com/dumindu/test_crate_hello_world"
+keywords = ["hello", "world"]
+license = "Apache-2.0"
+
+[dependencies]
+
+// 02. test_crate_hello_world/src/lib.rs
+//! A Simple Hello World Crate
+
+/// This function returns the greeting; `Hello, world!`
+pub fn hello() -> String {
+    ("Hello, world!").to_string()
+}
+
+#[cfg(test)]
+mod tests {
+
+    use super::hello;
+    
+    #[test]
+    fn test_hello() {
+        assert_eq!(hello(), "Hello, world!");
+    }
+}
+

πŸ’­ //! doc comments are used to write crate and module-level documentation. On other places, we have to use /// outside of the block. And when uploading a crate to crates.io, cargo generates the documentation from these doc comments and host it on docs.rs.

πŸ’‘ We have to add the description and license fields to Cargo.toml. Otherwise, we will get error: api errors: missing or empty metadata fields: description, license. Please see http://doc.crates.io/manifest.html

To upload this to crates.io,

  1. We have to create an account on crates.io to acquire an API token
  2. Then run cargo login <token> with that API token and cargo publish

πŸ“– This is how it describes on Cargo Docs with more details.

  • You’ll need an account on crates.io to acquire an API token. To do so, visit the home page and log in via a GitHub account (required for now). After this, visit your Account Settings page and run the cargo login command specified. +Ex. cargo login abcdefghijklmnopqrstuvwxyz012345
  • The next step is to package up your crate into a format that can be uploaded to crates.io. For this we’ll use the cargo package sub-command.
  • Now, it can be uploaded to crates.io with the cargo publish command.
  • If you’d like to skip the cargo package step, the cargo publish sub-command will automatically package up the local crate if a copy isn’t found already.

The name of our crate is test_crate_hello_world. So it can be found on, +πŸ“¦ https://crates.io/crates/test_crate_hello_world +πŸ“‘ https://docs.rs/test_crate_hello_world

πŸ’― crates.io supports readme files as well. To enable it, we have to add the readme field to Cargo.toml. Ex: readme="README.md"

πŸ—οΈ Okay then, Let’s see how we can use this from another crate.

// # Think we run,
+cargo new greetings
+
+// # It generates,
+greetings
+ β”œβ”€β”€ Cargo.toml
+ └── src
+    └── main.rs
+
+// # Think we modify following files,
+
+// 01. greetings/Cargo.toml
+[package]
+name = "greetings"
+version = "0.1.0"
+authors = ["Dumindu Madunuwan"]
+
+[dependencies]
+test_crate_hello_world = "0.1.0"
+
+// 02. greetings/src/main.rs
+extern crate test_crate_hello_world;
+
+fn main() {
+    println!("{}", test_crate_hello_world::hello());
+}
+

By default, Cargo looks dependencies on crates.io. So we have to add only the crate name and a version string to Cargo.toml and then run cargo build to fetch the dependencies and compile them.

\ No newline at end of file diff --git a/docs/docs/custom-error-types/index.html b/docs/docs/custom-error-types/index.html new file mode 100644 index 0000000..48ec9ff --- /dev/null +++ b/docs/docs/custom-error-types/index.html @@ -0,0 +1,228 @@ +Custom Error Types Β· Learning Rust +

Custom Error Types

Rust allow us to create our own Err types. We call them β€œCustom Error Types”.

Error trait

As you know traits define the functionality a type must provide. But we don’t always need to define new traits for common functionalities, because Rust standard library provides reusable traits which can be implemented on our own types. While creating custom error types the std::error::Error trait helps us to convert any type to an Err type.

use std::fmt::{Debug, Display};
+
+pub trait Error: Debug + Display {
+    fn source(&self) -> Option<&(Error + 'static)> { ... }
+}
+

As we discussed under traits inheritance, a trait can be inherited from another traits. trait Error: Debug + Display means Error trait inherits from fmt::Debug and fmt::Display traits.

// traits inside Rust standard library core fmt module/ std::fmt
+pub trait Display {
+    fn fmt(&self, f: &mut Formatter) -> Result<(), Error>;
+}
+
+pub trait Debug {
+    fn fmt(&self, f: &mut Formatter) -> Result<(), Error>;
+}
+
  • Display

    • How should the end user see this error as a message/ user-facing output.
    • Usually print via println!("{}") or eprintln!("{}")
  • Debug

    • How should display the Err while debugging/ programmer-facing output.
    • Usually print via println!("{:?}") or eprintln!("{:?}")
    • To pretty-print, println!("{:#?}") or eprintln!("{:#?}") can be used.
  • source()

    • The lower-level source of this error, if any.
    • Optional.

First, let’s see how to implement std::error::Error trait on a simplest custom error type.

use std::fmt;
+
+// Custom error type; can be any type which defined in the current crate
+// πŸ’‘ In here, we use a simple "unit struct" to simplify the example
+struct AppError;
+
+// Implement std::fmt::Display for AppError
+impl fmt::Display for AppError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "An Error Occurred, Please Try Again!") // user-facing output
+    }
+}
+
+// Implement std::fmt::Debug for AppError
+impl fmt::Debug for AppError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "{{ file: {}, line: {} }}", file!(), line!()) // programmer-facing output
+    }
+}
+
+// A sample function to produce an AppError Err
+fn produce_error() -> Result<(), AppError> {
+    Err(AppError)
+}
+
+fn main() {
+    match produce_error() {
+        Err(e) => eprintln!("{}", e), // An Error Occurred, Please Try Again!
+        _ => println!("No error"),
+    }
+
+    eprintln!("{:?}", produce_error()); // Err({ file: src/main.rs, line: 17 })
+}
+

Hope you understood the main points. Now, let’s see a custom error type with an error code and an error message.

use std::fmt;
+
+struct AppError {
+    code: usize,
+    message: String,
+}
+
+// Different error messages according to AppError.code
+impl fmt::Display for AppError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let err_msg = match self.code {
+            404 => "Sorry, Can not find the Page!",
+            _ => "Sorry, something is wrong! Please Try Again!",
+        };
+
+        write!(f, "{}", err_msg)
+    }
+}
+
+// A unique format for dubugging output
+impl fmt::Debug for AppError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(
+            f,
+            "AppError {{ code: {}, message: {} }}",
+            self.code, self.message
+        )
+    }
+}
+
+fn produce_error() -> Result<(), AppError> {
+    Err(AppError {
+        code: 404,
+        message: String::from("Page not found"),
+    })
+}
+
+fn main() {
+    match produce_error() {
+        Err(e) => eprintln!("{}", e), // Sorry, Can not find the Page!
+        _ => println!("No error"),
+    }
+
+    eprintln!("{:?}", produce_error()); // Err(AppError { code: 404, message: Page not found })
+
+    eprintln!("{:#?}", produce_error());
+    // Err(
+    //     AppError { code: 404, message: Page not found }
+    // )
+}
+

⭐️ Rust standard library provides not only reusable traits and also it facilitates to magically generate implementations for few traits via #[derive] attribute. Rust support derive std::fmt::Debug, to provide a default format for debug messages. So we can skip std::fmt::Debug implementation for custom error types and use #[derive(Debug)] before struct declaration.

For a struct #[derive(Debug)] prints, the name of the struct , { , comma-separated list of each field’s name and debug value and }.

use std::fmt;
+
+#[derive(Debug)] // derive std::fmt::Debug on AppError
+struct AppError {
+    code: usize,
+    message: String,
+}
+
+impl fmt::Display for AppError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let err_msg = match self.code {
+            404 => "Sorry, Can not find the Page!",
+            _ => "Sorry, something is wrong! Please Try Again!",
+        };
+
+        write!(f, "{}", err_msg)
+    }
+}
+
+fn produce_error() -> Result<(), AppError> {
+    Err(AppError {
+        code: 404,
+        message: String::from("Page not found"),
+    })
+}
+
+fn main() {
+    match produce_error() {
+        Err(e) => eprintln!("{}", e), // Sorry, Can not find the Page!
+        _ => println!("No error"),
+    }
+
+    eprintln!("{:?}", produce_error()); // Err(AppError { code: 404, message: Page not found })
+
+    eprintln!("{:#?}", produce_error());
+    // Err(
+    //     AppError {
+    //         code: 404,
+    //         message: "Page not found"
+    //     }
+    // )
+}
+

From trait

When writing real programs, we mostly have to deal with different modules, different std and third party crates at the same time. Each crate uses their own error types. However, if we are using our own error type, we should convert those errors into our error type. For these conversions, we can use the standardized trait std::convert::From.

// traits inside Rust standard library core convert module/ std::convert
+pub trait From<T>: Sized {
+  fn from(_: T) -> Self;
+}
+

πŸ’‘ As you know, String::from() function is used to create a String from &str data type. Actually this also an implementation of std::convert::From trait.

Let’s see how to implement std::convert::From trait on a custom error type.

use std::fs::File;
+use std::io;
+
+#[derive(Debug)]
+struct AppError {
+    kind: String,    // type of the error
+    message: String, // error message
+}
+
+// Implement std::convert::From for AppError; from io::Error
+impl From<io::Error> for AppError {
+    fn from(error: io::Error) -> Self {
+        AppError {
+            kind: String::from("io"),
+            message: error.to_string(),
+        }
+    }
+}
+
+fn main() -> Result<(), AppError> {
+    let _file = File::open("nonexistent_file.txt")?; // This generates an io::Error. But because of return type is Result<(), AppError>, it converts to AppError
+
+    Ok(())
+}
+
+
+// --------------- Run time error ---------------
+Error: AppError { kind: "io", message: "No such file or directory (os error 2)" }
+

In the above example, File::open(β€œnonexistent.txt”)? produces std::io::Error. But because of the return type is Result<(), AppError>, it converts to an AppError. Because of we are propagating the error from main() function, it prints the Debug representation of the Err.

In the above example we deal with only one std error type, std::io::Error. Let’s see some example which handles multiple std error types.

use std::fs::File;
+use std::io::{self, Read};
+use std::num;
+
+#[derive(Debug)]
+struct AppError {
+    kind: String,
+    message: String,
+}
+
+// Implement std::convert::From for AppError; from io::Error
+impl From<io::Error> for AppError {
+    fn from(error: io::Error) -> Self {
+        AppError {
+            kind: String::from("io"),
+            message: error.to_string(),
+        }
+    }
+}
+
+// Implement std::convert::From for AppError; from num::ParseIntError
+impl From<num::ParseIntError> for AppError {
+    fn from(error: num::ParseIntError) -> Self {
+        AppError {
+            kind: String::from("parse"),
+            message: error.to_string(),
+        }
+    }
+}
+
+fn main() -> Result<(), AppError> {
+    let mut file = File::open("hello_world.txt")?; // generates an io::Error, if can not open the file and converts to an AppError
+
+    let mut content = String::new();
+    file.read_to_string(&mut content)?; // generates an io::Error, if can not read file content and converts to an AppError
+
+    let _number: usize;
+    _number = content.parse()?; // generates num::ParseIntError, if can not convert file content to usize and converts to an AppError
+
+    Ok(())
+}
+
+
+// --------------- Few possible run time errors ---------------
+
+// 01. If hello_world.txt is a nonexistent file
+Error: AppError { kind: "io", message: "No such file or directory (os error 2)" }
+
+// 02. If user doesn't have relevant permission to access hello_world.txt
+Error: AppError { kind: "io", message: "Permission denied (os error 13)" }
+
+// 03. If hello_world.txt contains non-numeric content. ex Hello, world!
+Error: AppError { kind: "parse", message: "invalid digit found in string" }
+

πŸ”Ž Search about the implementation of std::io::ErrorKind, to see how to organize error types further.

\ No newline at end of file diff --git a/docs/docs/enums/index.html b/docs/docs/enums/index.html new file mode 100644 index 0000000..d689af8 --- /dev/null +++ b/docs/docs/enums/index.html @@ -0,0 +1,45 @@ +Enums Β· Learning Rust +

Enums

⭐️ An enum is a single type. It contains variants, which are possible values of the enum at a given time. For example,

enum Day {
+    Sunday,
+    Monday,
+    Tuesday,
+    Wednesday,
+    Thursday,
+    Friday,
+    Saturday
+}
+
+// The `Day` is the enum
+// Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are the variants
+

⭐️ Variants can be accessed through :: notation, ex. Day::Sunday

⭐️ Each enum variant can have,

  • No data (unit variant)
  • Unnamed ordered data (tuple variant)
  • Named data (struct variant)
enum FlashMessage {
+  Success, // A unit variant
+  Warning{ category: i32, message: String }, // A struct variant
+  Error(String) // A tuple variant
+}
+
+fn main() {
+  let mut form_status = FlashMessage::Success;
+  print_flash_message(form_status);
+
+  form_status = FlashMessage::Warning {category: 2, message: String::from("Field X is required")};
+  print_flash_message(form_status);
+
+  form_status = FlashMessage::Error(String::from("Connection Error"));
+  print_flash_message(form_status);
+}
+
+fn print_flash_message(m : FlashMessage) {
+  // Pattern matching with enum
+  match m {
+    FlashMessage::Success =>
+      println!("Form Submitted correctly"),
+    FlashMessage::Warning {category, message} => // Destructure, should use same field names
+      println!("Warning : {} - {}", category, message),
+    FlashMessage::Error(msg) =>
+      println!("Error : {}", msg)
+  }
+}
+
\ No newline at end of file diff --git a/docs/docs/error-and-none-propagation/index.html b/docs/docs/error-and-none-propagation/index.html new file mode 100644 index 0000000..1e3151e --- /dev/null +++ b/docs/docs/error-and-none-propagation/index.html @@ -0,0 +1,73 @@ +Error and None Propagation Β· Learning Rust +

Error and None Propagation

We should use panics like panic!(), unwrap(), expect() only if we can not handle the situation in a better way. Also if a function contains expressions which can produce either None or Err,

  • we can handle them inside the same function. Or,
  • we can return None and Err types immediately to the caller. So the caller can decide how to handle them.

πŸ’‘ None types no need to handle by the caller of the function always. But Rusts’ convention to handle Err types is, return them immediately to the caller to give more control to the caller to decide how to handle them.

? Operator

  • If an Option type has Some value or a Result type has a Ok value, the value inside them passes to the next step.
  • If the Option type has None value or the Result type has Err value, return them immediately to the caller of the function.

Example with Option type,

fn main() {
+    if complex_function().is_none() {
+        println!("X not exists!");
+    }
+}
+
+fn complex_function() -> Option<&'static str> {
+    let x = get_an_optional_value()?; // if None, returns immediately; if Some("abc"), set x to "abc"
+
+    // some other code, ex
+    println!("{}", x); // "abc" ; if you change line 19 `false` to `true` 
+
+    Some("")
+}
+
+fn get_an_optional_value() -> Option<&'static str> {
+
+    //if the optional value is not empty
+    if false {
+        return Some("abc");
+    }
+    
+    //else
+    None
+}
+

Example with Result Type,

fn main() {
+    // `main` function is the caller of `complex_function` function
+    // So we handle errors of complex_function(), inside main()
+    if complex_function().is_err() {
+        println!("Can not calculate X!");
+    }
+}
+
+fn complex_function() -> Result<u64, String> {
+    let x = function_with_error()?; // if Err, returns immediately; if Ok(255), set x to 255
+
+    // some other code, ex
+    println!("{}", x); // 255 ; if you change line 20 `true` to `false`
+
+    Ok(0)
+}
+
+fn function_with_error() -> Result<u64, String> {
+    //if error happens
+    if true {
+        return Err("some message".to_string());
+    }
+
+    // else, return valid output
+    Ok(255)
+}
+

try!()

⭐ ? operator was added in Rust version 1.13. try!() macro is the old way to propagate errors before that. So we should avoid using this now.

  • If a Result type has Ok value, the value inside it passes to the next step. If it has Err value, returns it immediately to the caller of the function.
// using `?`
+let x = function_with_error()?; // if Err, returns immediately; if Ok(255), set x to 255
+
+// using `try!()`
+let x = try!(function_with_error());
+

Error propagation fromΒ main()

Before Rust version 1.26, we couldn’t propagate Result and Option types from the main() function. But now, we can propagate Result types from the main() function and it prints the Debug representation of the Err.

πŸ’‘ We are going to discuss about Debug representations under Error trait section.

use std::fs::File;
+
+fn main() -> std::io::Result<()> {
+    let _ = File::open("not-existing-file.txt")?;
+
+    Ok(()) // Because of the default return value of Rust functions is an empty tuple/ ()
+}
+
+// Because of the program can not find not-existing-file.txt , it produces,
+//    Err(Os { code: 2, kind: NotFound, message: "No such file or directory" })
+// While propagating error, the program prints,
+//    Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
+

πŸ’― If you want to know about the all kind of errors std::fs::File::open() can produce, check the error list on std::fs::OpenOptions.

\ No newline at end of file diff --git a/docs/docs/functions-02/index.html b/docs/docs/functions-02/index.html new file mode 100644 index 0000000..d589eb4 --- /dev/null +++ b/docs/docs/functions-02/index.html @@ -0,0 +1,32 @@ +Functions (02) Β· Learning Rust +

Functions (02)

Functions are the first line of organization in any program.

fn main() {
+  greet(); // Do one thing
+  ask_location(); // Do another thing
+}
+
+fn greet() {
+  println!("Hello!");
+}
+
+fn ask_location() {
+  println!("Where are you from?");
+}
+

We can add unit tests in the same file.

fn main() {
+    greet();
+}
+
+fn greet() -> String {
+    "Hello, world!".to_string()
+}
+
+#[test] // Test attribute indicates this is a test function
+fn test_greet() {
+    assert_eq!("Hello, world!", greet())
+}
+
+// πŸ’‘ Always put test functions inside a tests module with #[cfg(test)] attribute. 
+// cfg(test) module compiles only when running tests. We discuss more about this in the next section.
+

πŸ’­ An attribute is a general, free-form metadatum that is interpreted according to name, convention, and language and compiler version.

\ No newline at end of file diff --git a/docs/docs/functions/index.html b/docs/docs/functions/index.html new file mode 100644 index 0000000..8a47713 --- /dev/null +++ b/docs/docs/functions/index.html @@ -0,0 +1,66 @@ +Functions Β· Learning Rust +

Functions

Named functions

  • Named functions are declared with the keyword fn
  • When using arguments, you must declare the data types.
  • By default, functions return an empty tuple/ (). If you want to return a value, the return type must be specified after ->

i. Hello world

fn main() {
+    println!("Hello, world!");
+}
+

ii. Passing arguments

fn print_sum(a: i8, b: i8) {
+    println!("sum is: {}", a + b);
+}
+

iii. Returning values

// 01. Without the return keyword. Only the last expression returns.
+fn plus_one(a: i32) -> i32 {
+    a + 1
+    // There is no ending ; in the above line.
+    // It means this is an expression which equals to `return a + 1;`.
+}
+
// 02. With the return keyword.
+fn plus_two(a: i32) -> i32 {
+    return a + 2;
+    // Should use return keyword only on conditional/ early returns.
+    // Using return keyword in the last expression is a bad practice.
+}
+

iv. Function pointers, Usage as a Data Type

fn main() {
+    // 01. Without type declarations.
+    let p1 = plus_one;
+    let x = p1(5); // 6
+
+    // 02. With type declarations.
+    let p1: fn(i32) -> i32 = plus_one;
+    let x = p1(5); // 6
+}
+
+fn plus_one(a: i32) -> i32 {
+    a + 1
+}
+

Closures

  • Also known as anonymous functions or lambda functions.
  • The data types of arguments and returns are optional ⃰ⁱᡛ.

Example with a named function, before using closures.

fn main() {
+  let x = 2;
+  println!("{}", get_square_value(x));
+}
+
+fn get_square_value(i: i32) -> i32 {
+    i * i
+}
+

i. With optional type declarations of input and return types

fn main() {
+    let x = 2;
+    let square = |i: i32| -> i32 { // Input parameters are passed inside | | and expression body is wrapped within { }
+        i * i
+    };
+    println!("{}", square(x));
+}
+

ii. Without type declarations of input and return types

fn main() {
+    let x = 2;
+    let square = |i| i * i; // { } are optional for single-lined closures
+    println!("{}", square(x));
+}
+

iii. With optional type declarations; Creating and calling together

fn main() {
+    let x = 2;
+    let x_square = |i: i32| -> i32 { i * i }(x); // { } are mandatory while creating and calling same time.
+    println!("{}", x_square);
+}
+

iv. Without optional type declarations; Creating and calling together

fn main() {
+    let x = 2;
+    let x_square = |i| -> i32 { i * i }(x); // ⭐️ The return type is mandatory.
+    println!("{}", x_square);
+}
+
\ No newline at end of file diff --git a/docs/docs/generics/index.html b/docs/docs/generics/index.html new file mode 100644 index 0000000..7ec8973 --- /dev/null +++ b/docs/docs/generics/index.html @@ -0,0 +1,91 @@ +Generics Β· Learning Rust +

Generics

πŸ“– Sometimes, when writing a function or data type, we may want it to work for multiple types of arguments. In Rust, we can do this with generics.

πŸ’­ The concept is, instead of declaring a specific data type we use an uppercase letter(or PascalCase identifier). ex, instead of xΒ : u8 we use xΒ : TΒ . but we have to inform to the compiler that T is a generic type(can be any type) by adding <T> at first.

Generalizing functions

fn takes_anything<T>(x: T) { // x has type T, T is a generic type
+}
+
+fn takes_two_of_the_same_things<T>(x: T, y: T) { // Both x and y has the same type
+}
+
+fn takes_two_things<T, U>(x: T, y: U) { // Multiple types
+}
+

Generalizing structs

struct Point<T> {
+  x: T,
+  y: T,
+}
+
+fn main() {
+  let point_a = Point { x: 0, y: 0 }; // T is a int type
+  let point_b = Point { x: 0.0, y: 0.0 }; // T is a float type
+}
+
+// πŸ”Ž When adding an implementation for a generic struct, the type parameters should be declared after the impl as well
+//   impl<T> Point<T> {
+

Generalizing enums

enum Option<T> {
+    Some(T),
+    None,
+}
+
+enum Result<T, E> {
+    Ok(T),
+    Err(E),
+}
+

⭐️ Above Option and Result types are kind of special generic types which are already defined in Rust’s standard library.Β 

  • An optional value can have either Some value or no value/ None.
  • A result can represent either success/ Ok or failure/ Err

Usages of Option

// 01 - - - - - - - - - - - - - - - - - - - - - -
+fn get_id_by_username(username: &str) -> Option<usize> {
+    // if username can be found in the system, set userId
+        return Some(userId);
+    // else
+        None
+}
+
+// πŸ’­ So, on the above function, instead of setting return type as usize
+//   set return type as Option<usize>
+// Instead of return userId, return Some(userId)
+//   else None (πŸ’‘remember? last return statement no need return keyword and ending ;)
+
+// 02 - - - - - - - - - - - - - - - - - - - - - -
+struct Task {
+    title: String,
+    assignee: Option<Person>,
+}
+
+// πŸ’­ Instead of assignee: Person, we use Option<Person>
+// because the task has not been assigned to a specific person
+
+// - - - - - - - - - - - - - - - - - - - - - - -
+// When using Option types as return types on functions
+// we can use pattern matching to catch the relevant return type(Some/None) when calling them
+
+fn main() {
+    let username = "anonymous";
+    match get_id_by_username(username) {
+        None => println!("User not found"),
+        Some(i) => println!("User Id: {}", i)
+    }
+}
+

Usages of Result

πŸ“– The Option type is a way to use Rust’s type system to express the possibility of absence. Result expresses the possibility of error.

// - - - - - - - - - - - - - - - - - - - - - -
+fn get_word_count_from_file(file_name: &str) -> Result<u32, &str> {
+  // if the file is not found on the system, return error
+    return Err("File can not be found!")
+  // else, count and return the word count
+    // let mut word_count: u32; ....
+    Ok(word_count)
+}
+
+// πŸ’­ On the above function,
+// instead panic(break) the app, when the file can not be found; return Err(something)
+// or when it could get the relevant data; return Ok(data)
+
+
+// - - - - - - - - - - - - - - - - - - - - - - -
+// We can use pattern matching to catch the relevant return type(Ok/Err) when calling it
+
+fn main() {
+    let mut file_name = "file_a";
+    match get_word_count_from_file(file_name) {
+        Ok(i) => println!("Word Count: {}", i),
+        Err(e) => println!("Error: {}", e)
+    }
+}
+

πŸ”Ž Many useful methods have been implemented around Option and Result types. More information can be found on std::option::Option and std::result::Result pages on Rust doc.

⭐️ Also more practical examples of options & results can be found on Error Handling section in Rust doc.

\ No newline at end of file diff --git a/docs/docs/hello-world/index.html b/docs/docs/hello-world/index.html new file mode 100644 index 0000000..e80ac66 --- /dev/null +++ b/docs/docs/hello-world/index.html @@ -0,0 +1,36 @@ +Hello World Β· Learning Rust +

Hello World

Hello, World!

fn main() {
+    println!("Hello, world!");
+}
+

fn means function. The main function is the beginning of every Rust program.
println!() prints text to the console and its ! indicates that it’s a macro rather than a function.

πŸ’‘ Rust files should have .rs file extension and if you’re using more than one word for the file name, follow the snake_case convention.

  • Save the above code in file.rs , but it can be any name with .rs extension.
  • Compile it with rustc file.rs
  • Execute it with ./file on Linux and Mac or file.exe on Windows

Rust Playground

Rust Playground is a web interface for running Rust code.

Rust Playground

πŸ‘¨β€πŸ« Before going to the next…

  • These are the other usages of the println!() macro,
fn main() {
+    println!("{}, {}!", "Hello", "world"); // Hello, world!
+    println!("{0}, {1}!", "Hello", "world"); // Hello, world!
+    println!("{greeting}, {name}!", greeting = "Hello", name = "world"); // Hello, world!
+
+    let (greeting, name) = ("Hello", "world"); // πŸ’‘ Two Variable bindings declare & initialize in one line.
+    println!("{greeting}, {name}!"); // Hello, world!
+
+    println!("{:?}", [1, 2, 3]); // [1, 2, 3]
+    println!("{:#?}", [1, 2, 3]);
+    /*
+        [
+            1,
+            2,
+            3
+        ]
+    */
+
+    // πŸ”Ž The format! macro is used to store the formatted string.
+    let x = format!("{}, {}!", "Hello", "world");
+    println!("{}", x); // Hello, world!
+
+    // πŸ’‘ Rust has a print!() macro as well
+    print!("Hello, world!"); // Without new line
+    println!(); // A new line
+
+    print!("Hello, world!\n"); // With new line
+}
+
\ No newline at end of file diff --git a/docs/docs/impls-and-traits/index.html b/docs/docs/impls-and-traits/index.html new file mode 100644 index 0000000..3cde3c8 --- /dev/null +++ b/docs/docs/impls-and-traits/index.html @@ -0,0 +1,144 @@ +Impls & Traits Β· Learning Rust +

Impls & Traits

πŸ’‘ When we discussed about C-like structs, I mentioned that those are similar to classes in OOP languages but without their methods. impls are used to define methods for Rust structs and enums.

πŸ’‘ Traits are kind of similar to interfaces in OOP languages. They are used to define the functionality a type must provide. Multiple traits can be implemented for a single type.

⭐️️ But traits can also include default implementations of methods. Default methods can be overridden when implementing types.

Impls without traits

struct Player {
+    first_name: String,
+    last_name: String,
+}
+
+impl Player {
+    fn full_name(&self) -> String {
+        format!("{} {}", self.first_name, self.last_name)
+    }
+}
+
+fn main() {
+    let player_1 = Player {
+        first_name: "Rafael".to_string(),
+        last_name: "Nadal".to_string(),
+    };
+
+    println!("Player 01: {}", player_1.full_name());
+}
+
+// ⭐️ Implementation must appear in the same crate as the self type
+

Impls & traits, without default methods

struct Player {
+    first_name: String,
+    last_name: String,
+}
+
+trait FullName {
+    fn full_name(&self) -> String;
+}
+
+impl FullName for Player {
+    fn full_name(&self) -> String {
+        format!("{} {}", self.first_name, self.last_name)
+    }
+}
+
+fn main() {
+    let player_2 = Player {
+        first_name: "Roger".to_string(),
+        last_name: "Federer".to_string(),
+    };
+
+    println!("Player 02: {}", player_2.full_name());
+}
+
+// πŸ”Ž Other than functions, traits can contain constants and types.
+
+// πŸ’‘ And also in Rust, new traits can be implemented for existing types even for types like i8, f64 and etc.
+// Same way existing traits can be implemented for new types you are creating.
+

Impls, traits & default methods

trait Foo {
+    fn bar(&self);
+    fn baz(&self) { println!("We called baz."); }
+}
+

⭐️ As you can see methods take a special first parameter, the type itself. It can be either self, &self, or &mut self; self if it’s a value on the stack (taking ownership), &self if it’s a reference, and &mut self if it’s a mutable reference.

Impls with Associated functions

Some other languages support static methods. At such times, we call a function directly through the class without creating an object. In Rust, we call them Associated Functions. we useΒ :: instead ofΒ . when calling them from the struct. +ex. Person::new(β€œElon Musk Jr”);

struct Player {
+    first_name: String,
+    last_name: String,
+}
+
+impl Player {
+    fn new(first_name: String, last_name: String) -> Player {
+        Player {
+            first_name: first_name,
+            last_name: last_name,
+        }
+    }
+
+    fn full_name(&self) -> String {
+        format!("{} {}", self.first_name, self.last_name)
+    }
+}
+
+fn main() {
+    let player_name = Player::new("Serena".to_string(), "Williams".to_string()).full_name();
+    println!("Player: {}", player_name);
+}
+
+// We have used :: notation for `new()` and . notation for `full_name()`
+
+// πŸ”Ž Also in here, instead of using new() and full_name() separately as two expressions, 
+// we can use Method Chaining. ex. `player.add_points(2).get_point_count();`
+

Traits with generics

trait From<T> {
+    fn from(T) -> Self;
+}
+
+impl From<u8> for u16 {
+    //...
+}
+impl From<u8> for u32{
+    //...
+}
+// Should specify after the trait name like generic functions
+

Traits inheritance

trait Person {
+    fn full_name(&self) -> String;
+}
+
+trait Employee : Person { // Employee inherits from person trait
+  fn job_title(&self) -> String;
+}
+
+trait ExpatEmployee : Employee + Expat { // ExpatEmployee inherits from Employee and Expat traits
+  fn additional_tax(&self) -> f64;
+}
+

Trait objects

πŸ”Ž While Rust favors static dispatch, it also supports dynamic dispatch through a mechanism called β€˜trait objects.’

πŸ…† Dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time.

trait GetSound {
+    fn get_sound(&self) -> String;
+}
+
+struct Cat {
+    sound: String,
+}
+
+impl GetSound for Cat {
+    fn get_sound(&self) -> String {
+        self.sound.clone()
+    }
+}
+
+struct Bell {
+    sound: String,
+}
+
+impl GetSound for Bell {
+    fn get_sound(&self) -> String {
+        self.sound.clone()
+    }
+}
+
+
+fn make_sound<T: GetSound>(t: &T) {
+    println!("{}!", t.get_sound())
+}
+
+fn main() {
+    let kitty = Cat { sound: "Meow".to_string() };
+    let the_bell = Bell { sound: "Ding Dong".to_string() };
+
+    make_sound(&kitty); // Meow!
+    make_sound(&the_bell); // Ding Dong!
+}
+
\ No newline at end of file diff --git a/docs/docs/index.html b/docs/docs/index.html new file mode 100644 index 0000000..cd3b06b --- /dev/null +++ b/docs/docs/index.html @@ -0,0 +1,2 @@ +https://learning-rust.github.io/docs/overview/ + \ No newline at end of file diff --git a/docs/docs/index.xml b/docs/docs/index.xml new file mode 100644 index 0000000..08d4674 --- /dev/null +++ b/docs/docs/index.xml @@ -0,0 +1,503 @@ +Docs on Learning Rusthttps://learning-rust.github.io/docs/Recent content in Docs on Learning RustHugoen-USBorrowinghttps://learning-rust.github.io/docs/borrowing/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/borrowing/<p>In real life applications, most of the times we have to pass variable bindings to other functions or assign them to other variable bindings. In this case, we are <strong>referencing</strong> the original binding; <strong>borrow</strong> the data of it.</p> +<h2 id="what-is-borrowing">What is Borrowing?</h2> +<blockquote> +<p><a href="https://github.com/nikomatsakis/rust-tutorials-keynote/blob/master/Ownership%20and%20Borrowing.pdf" target="_blank" >Borrow (verb)</a><br> +To receive something with the promise of returning it.</p></blockquote> +<h2 id="shared--mutable-borrowings">Shared &amp; Mutable borrowings</h2> +<p>⭐️ There are two types of Borrowing,</p> +<ol> +<li> +<p><strong>Shared Borrowing</strong> <code>(&amp;T)</code></p> +<ul> +<li>A piece of data can be <strong>borrowed by a single or multiple users</strong>, but <strong>data should not be altered</strong>.</li> +</ul> +</li> +<li> +<p><strong>Mutable Borrowing</strong> <code>(&amp;mut T)</code></p>Cargo, Crates and Basic Project Structurehttps://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/<h2 id="cargo">Cargo</h2> +<p>Cargo is Rust’s built-in package manager and build system. It also supports the following actions,</p> +<table> + <thead> + <tr> + <th>Command</th> + <th>Action</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>cargo new</code></td> + <td>Create a new project</td> + </tr> + <tr> + <td><code>cargo init</code></td> + <td>Create a new project in an existing directory</td> + </tr> + <tr> + <td><code>cargo check</code></td> + <td>Verify the project compiles without errors</td> + </tr> + <tr> + <td><code>cargo build</code></td> + <td>Build the executable</td> + </tr> + <tr> + <td><code>cargo run</code></td> + <td>Build the executable and run</td> + </tr> + </tbody> +</table> +<blockquote> +<p>πŸ’‘ The <code>cargo check</code> command verifies that the project compiles without errors, without producing an executable. +Thus, it is often faster than <code>cargo build</code>.</p>Code Organizationhttps://learning-rust.github.io/docs/code-organization/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/code-organization/<p>When a single code block is getting larger, it should be decomposed into smaller pieces and should be organized in a proper manner. Rust supports different levels of code organization.</p> +<h2 id="1-functions">1. Functions</h2> +<h2 id="2-modules">2. Modules</h2> +<p>Can be mapped to a,</p> +<ul> +<li><strong>Inline module</strong></li> +<li><strong>File</strong></li> +<li><strong>Directory hierarchy</strong></li> +</ul> +<h2 id="3-crates">3. Crates</h2> +<p>Can be mapped to a,</p> +<ul> +<li> +<p><strong>lib.rs file on the same executable crate</strong></p> +</li> +<li> +<p><strong>Dependency crate specified on Cargo.toml</strong></p> +<p>Can be specified from,</p> +<ul> +<li><strong>Path</strong></li> +<li><strong>Git repository</strong></li> +<li><strong>crates.io</strong></li> +</ul> +</li> +</ul> +<h2 id="4-workspaces">4. Workspaces</h2> +<p>Helps to manage multiple crates as a single project.</p>Combinatorshttps://learning-rust.github.io/docs/combinators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/combinators/<h2 id="what-is-a-combinator">What is a combinator?</h2> +<ul> +<li> +<p>One meaning of β€œcombinator” is a more informal sense referring to the <strong>combinator pattern</strong>, a style of organizing libraries centered around the idea of combining things. Usually there is <strong>some type T</strong>, some <strong>functions for constructing β€œprimitive” values of type T</strong>, and some β€œ<strong>combinators</strong>” which can <strong>combine values of type T</strong> in various ways to <strong>build up more complex values of type T</strong>. The other definition is <strong>&ldquo;function with no free variables&rdquo;</strong>. +__ <a href="https://wiki.haskell.org/Combinator" target="_blank" >wiki.haskell.org</a></p>Comments and Documenting the codehttps://learning-rust.github.io/docs/comments-and-documenting-the-code/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/comments-and-documenting-the-code/<h2 id="comments">Comments</h2> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// Line comments +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="cm">/* Block comments */</span><span class="w"> +</span></span></span></code></pre></div><p>Nested block comments are supported.</p> +<p>πŸ’‘ <strong>By convention, try to avoid using block comments. Use line comments instead.</strong></p> +<h2 id="doc-comments">Doc Comments</h2> +<p><a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#cargo" >As we discussed</a>, we can generate the project documentation via <a href="https://doc.rust-lang.org/stable/rustdoc/" target="_blank" >rustdoc</a> by running the <strong><code>cargo doc</code></strong> command. It uses the doc comments to generate the documentation.</p> +<p>πŸ’‘ Usually we are adding doc comments on library crates. Also, we can use <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank" >Markdown notations</a> inside the doc comments.</p>Control Flowshttps://learning-rust.github.io/docs/control-flows/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/control-flows/<h2 id="if---else-if---else">if - else if - else</h2> +<ul> +<li>Using only <code>if</code> block.</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, child!&#34;</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><ul> +<li>Using only <code>if</code> and <code>else</code> blocks.</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Even&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Odd&#34;</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><ul> +<li>Using with <code>let</code> statement.</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span>: <span class="kt">u8</span> <span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">is_below_eighteen</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">false</span><span class="w"> </span><span class="p">};</span><span class="w"> </span><span class="c1">// true +</span></span></span></code></pre></div><ul> +<li>More examples,</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// i. A simple example +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Small&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Medium&#34;</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Large&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// ii. Let&#39;s refactor above code +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&#34;Small&#34;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&#34;Medium&#34;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&#34;Large&#34;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Current team size : </span><span class="si">{}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium +</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// iii. Let&#39;s refactor further +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Small&#34;</span><span class="w"> </span><span class="c1">// ⭐️ no ; +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Medium&#34;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Large&#34;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">};</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Current team size : </span><span class="si">{}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">team_size</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium +</span></span></span></code></pre></div><p>⭐️ <strong>Return data type should be the same on each block when using this as an expression.</strong></p>Crateshttps://learning-rust.github.io/docs/crates/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/crates/<p>πŸ’­ Crates are a bit similar to the packages in some other languages. Crates compile individually. If the crate has child file modules, those files will get merged with the crate file and compile as a single unit.</p> +<p>πŸ’­ A crate can produce an executable/ a binary or a library. <code>src/main.rs</code> is the crate root/ entry point for a binary crate and <code>src/lib.rs</code> is the entry point for a library crate.</p>Custom Error Typeshttps://learning-rust.github.io/docs/custom-error-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/custom-error-types/<p>Rust allow us to create our own <code>Err</code> types. We call them β€œ<em>Custom Error Types</em>”.</p> +<h2 id="error-trait">Error trait</h2> +<p>As you know <strong>traits define the functionality a type must provide</strong>. But we don’t always need to define new traits for common functionalities, because Rust <strong>standard library provides reusable traits</strong> which can be implemented on our own types. While creating custom error types the <a href="https://doc.rust-lang.org/std/error/trait.Error.html" target="_blank" ><code>std::error::Error</code> trait</a> helps us to convert any type to an <code>Err</code> type.</p>Enumshttps://learning-rust.github.io/docs/enums/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/enums/<p>⭐️ An <strong>enum</strong> is a single type. It contains <strong>variants</strong>, which are possible values of the enum at a given time. For example,</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">enum</span> <span class="nc">Day</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Sunday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Monday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Tuesday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Wednesday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Thursday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Friday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Saturday</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// The `Day` is the enum +</span></span></span><span class="line"><span class="cl"><span class="c1">// Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are the variants +</span></span></span></code></pre></div><p>⭐️ Variants can be accessed throughΒ :: notation, ex. Day::Sunday</p> +<p>⭐️ Each enum <strong>variant</strong> can have,</p>Error and None Propagationhttps://learning-rust.github.io/docs/error-and-none-propagation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/error-and-none-propagation/<p>We should use panics like <code>panic!()</code>, <code>unwrap()</code>, <code>expect()</code> only if we can not handle the situation in a better way. Also if a function contains expressions which can produce either <code>None</code> or <code>Err</code>,</p> +<ul> +<li>we can handle them inside the same function. Or,</li> +<li>we can return <code>None</code> and <code>Err</code> types immediately to the caller. So the caller can decide how to handle them.</li> +</ul> +<p>πŸ’‘ <code>None</code> types no need to handle by the caller of the function always. But Rusts’ convention to handle <strong><code>Err</code></strong> types is, <strong>return them immediately to the caller to give more control to the caller to decide how to handle them.</strong></p>Functionshttps://learning-rust.github.io/docs/functions/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions/<h2 id="named-functions">Named functions</h2> +<ul> +<li>Named functions are declared with the keyword <strong><code>fn</code></strong></li> +<li>When using <strong>arguments</strong>, you <strong>must declare the data types</strong>.</li> +<li>By default, functions <strong>return an empty <a href="https://learning-rust.github.io/docs/primitive-data-types/#tuple" >tuple</a>/ <code>()</code></strong>. If you want to return a value, the <strong>return type must be specified</strong> after <strong><code>-&gt;</code></strong></li> +</ul> +<h3 id="i-hello-world">i. Hello world</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h3 id="ii-passing-arguments">ii. Passing arguments</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">print_sum</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i8</span><span class="p">,</span><span class="w"> </span><span class="n">b</span>: <span class="kt">i8</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;sum is: </span><span class="si">{}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h3 id="iii-returning-values">iii. Returning values</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 01. Without the return keyword. Only the last expression returns. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// There is no ending ; in the above line. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// It means this is an expression which equals to `return a + 1;`. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 02. With the return keyword. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_two</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// Should use return keyword only on conditional/ early returns. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// Using return keyword in the last expression is a bad practice. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h3 id="iv-function-pointers-usage-as-a-data-type">iv. Function pointers, Usage as a Data Type</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 01. Without type declarations. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 02. With type declarations. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span>: <span class="nc">fn</span><span class="p">(</span><span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h2 id="closures">Closures</h2> +<ul> +<li>Also known as <strong>anonymous functions</strong> or <strong>lambda functions</strong>.</li> +<li>The <strong>data types of arguments and returns are optional <a href="#iv-without-optional-type-declarations-creating-and-calling-together" > ⃰ⁱᡛ</a></strong>.</li> +</ul> +<p>Example with a named function, before using closures.</p>Functions (02)https://learning-rust.github.io/docs/functions-02/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions-02/<p>Functions are the first line of organization in any program.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do one thing +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="n">ask_location</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do another thing +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">ask_location</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Where are you from?&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>We can add unit tests in the same file.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span>-&gt; <span class="nb">String</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Hello, world!&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">()</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="cp">#[test]</span><span class="w"> </span><span class="c1">// Test attribute indicates this is a test function +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">test_greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">assert_eq!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">greet</span><span class="p">())</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// πŸ’‘ Always put test functions inside a tests module with #[cfg(test)] attribute. +</span></span></span><span class="line"><span class="cl"><span class="c1">// cfg(test) module compiles only when running tests. We discuss more about this in the next section. +</span></span></span></code></pre></div><blockquote> +<p>πŸ’­ An <a href="https://doc.rust-lang.org/reference/attributes.html" target="_blank" >attribute</a> is a general, free-form <strong>metadatum</strong> that is interpreted according to name, convention, and language and compiler version.</p>Genericshttps://learning-rust.github.io/docs/generics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/generics/<blockquote> +<p><a href="https://doc.rust-lang.org/beta/book/first-edition/generics.html" target="_blank" >πŸ“–</a> Sometimes, when writing a function or data type, we may want it to work for multiple types of arguments. In Rust, we can do this with generics.</p></blockquote> +<p>πŸ’­ The concept is, instead of declaring a specific data type we use an uppercase letter(or <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a> identifier). ex, <strong>instead of xΒ : u8</strong> we use <strong>xΒ : T</strong>Β . but we have to inform to the compiler that T is a generic type(can be any type) by adding <code>&lt;T&gt;</code> at first.</p>Hello Worldhttps://learning-rust.github.io/docs/hello-world/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/hello-world/<h2 id="hello-world">Hello, World!</h2> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p><code>fn</code> means function. The <code>main</code> function is the beginning of every Rust program.<br> +<code>println!()</code> prints text to the console and its <code>!</code> indicates that it’s a <a href="https://doc.rust-lang.org/book/ch19-06-macros.html" target="_blank" >macro</a> rather than a function.</p> +<blockquote> +<p>πŸ’‘ Rust files should have <code>.rs</code> file extension and if you’re using more than one word for the file name, follow the <a href="https://en.wikipedia.org/wiki/Snake_case" target="_blank" >snake_case</a> convention.</p></blockquote> +<ul> +<li>Save the above code in <code>file.rs</code> , but it can be any name with <code>.rs</code> extension.</li> +<li>Compile it with <code>rustc file.rs</code></li> +<li>Execute it with <code>./file</code> on Linux and Mac or <code>file.exe</code> on Windows</li> +</ul> +<h2 id="rust-playground">Rust Playground</h2> +<p><a href="https://play.rust-lang.org/" target="_blank" >Rust Playground</a> is a web interface for running Rust code.</p>Impls & Traitshttps://learning-rust.github.io/docs/impls-and-traits/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/impls-and-traits/<p>πŸ’‘ When we discussed about <strong>C-like structs</strong>, I mentioned that those are <strong>similar to classes</strong> in OOP languages <strong>but without their methods</strong>. <strong>impls</strong> are <strong>used to define methods</strong> for Rust structs and enums.</p> +<p>πŸ’‘ <strong>Traits</strong> are kind of <strong>similar to interfaces</strong> in OOP languages. They are used to define the functionality a type must provide. Multiple traits can be implemented for a single type.</p> +<p>⭐️️ But traits <strong>can also include default implementations of methods</strong>. Default methods can be overridden when implementing types.</p>Installationhttps://learning-rust.github.io/docs/installation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/installation/<h2 id="rustup">Rustup</h2> +<p>There are many ways to install Rust on your system. For the moment the official way to install Rust is using <a href="https://rustup.rs/" target="_blank" >Rustup</a>.</p> +<p><a href="https://rust-lang.github.io/rustup/index.html" target="_blank" >πŸ“–</a> Rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between <strong>stable, beta, and nightly</strong> compilers and keep them updated. It also makes cross-compiling simpler with binary builds of the standard library for common platforms.</p> +<p><a href="https://rust-lang.github.io/rustup/installation/index.html" target="_blank" >πŸ“–</a> Rustup installs <strong><code>rustc</code>, <code>cargo</code>, <code>rustup</code></strong> and other standard tools to Cargo&rsquo;s <code>bin</code> directory. On Unix it is located at <code>$HOME/.cargo/bin</code> and on Windows at <code>%USERPROFILE%\.cargo\bin</code>. This is the same directory that <code>cargo install</code> will install Rust programs and Cargo plugins.</p>Lifetimeshttps://learning-rust.github.io/docs/lifetimes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/lifetimes/<p>When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.</p> +<p>Think,</p> +<ul> +<li>We have a <strong>variable binding</strong>, <code>a</code>.</li> +<li>We are <strong>referencing</strong> the value of <code>a</code>, <strong>from another variable binding</strong> <code>x</code>. +We have to make sure that <strong><code>a</code> lives until we stop using <code>x</code></strong>.</li> +</ul> +<blockquote> +<p>πŸ”Ž <strong>Memory management</strong> is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used <strong>Manual Memory Management</strong> which <strong>requires the programmer to give manual instructions</strong> to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented <strong>Garbage collection</strong>(GC), a form of <strong>Automatic Memory Management</strong>(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However <strong>Objective-C and Swift</strong> provide similar functionality through <strong>Automatic Reference Counting</strong>(ARC).</p>Moduleshttps://learning-rust.github.io/docs/modules/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/modules/<h2 id="01-in-the-same-file">01. In the same file</h2> +<p>Related code and data are grouped into a module and stored in the same file.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// ⭐️ By default, everything inside a module is private +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// ⭐️ So function has to be public to access from outside +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>Modules can also be nested.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>Private functions can be called from the same module or from a child module.</p>Operatorshttps://learning-rust.github.io/docs/operators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/operators/<ul> +<li> +<h2 id="arithmetic-operators">Arithmetic Operators</h2> +</li> +</ul> +<p><code>+ - * / %</code></p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">5</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//6 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//4 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//10 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">// ⭐️ 2 not 2.5 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//1 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">5.0</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mf">2.0</span><span class="p">;</span><span class="w"> </span><span class="c1">//2.5 +</span></span></span></code></pre></div><ul> +<li> +<h2 id="comparison-operators">Comparison Operators</h2> +</li> +</ul> +<p><code>== != &lt; &gt; &lt;= &gt;=</code></p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&lt;=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">h</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&gt;=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// πŸ”Ž +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">&#39;a&#39;</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="sc">&#39;A&#39;</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span></code></pre></div><ul> +<li> +<h2 id="logical-operators">Logical Operators</h2> +</li> +</ul> +<p><code>! &amp;&amp; ||</code></p>Option and Resulthttps://learning-rust.github.io/docs/option-and-result/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/option-and-result/<h2 id="why-option-and-result">Why Option and Result?</h2> +<p>Many languages use <strong><code>null</code>\ <code>nil</code>\ <code>undefined</code> types</strong> to represent empty outputs, and <strong><code>Exceptions</code></strong> to handle errors. Rust skips using both, especially to prevent issues like <strong>null pointer exceptions, sensitive data leakages through exceptions</strong>, etc. Instead, Rust provides two special <strong>generic enums</strong>;<code>Option</code> and <code>Result</code> to deal with above cases.</p> +<blockquote> +<p>πŸ’­ In the previous sections, we have discussed about the basics of <a href="https://learning-rust.github.io/docs/enums" >enums</a>, <a href="https://learning-rust.github.io/docs/generics" >generics</a> and <a href="https://learning-rust.github.io/docs/generics/#generalizing-enums" ><code>Result</code> &amp; <code>Option</code> types</a>.</p>Overviewhttps://learning-rust.github.io/docs/overview/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/overview/<h2 id="about-me">About me</h2> +<blockquote> +<p>πŸ§‘β€πŸ’» I am an expat working in Singapore as a Go Backend and DevOps Engineer. Feel free to reach out if you find any mistakes or anything that needs to be changed, including spelling or grammar errors. Alternatively, you can create a pull request, open an issue, or <a href="https://gist.github.com/dumindu/00a0be2d175ed5ff3bc3c17bbf1ca5b6" target="_blank" >share your awesome ideas in this gist</a>. Good luck with learning Rust!</p></blockquote> +<p><a href="https://github.com/learning-rust/learning-rust.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-rust/learning-rust.github.io?style=for-the-badge&amp;logo=rust&amp;label=learning-rust.github.io&amp;logoColor=333333&amp;labelColor=f9f9f9&amp;color=F46623" alt="learning-rust.github.io"></a> +<a href="https://learning-cloud-native-go.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-cloud-native-go/learning-cloud-native-go.github.io?style=for-the-badge&amp;logo=go&amp;logoColor=333333&amp;label=learning-cloud-native-go.github.io&amp;labelColor=f9f9f9&amp;color=00ADD8" alt="learning-cloud-native-go.github.io"></a></p> +<p><a href="https://github.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/dumindu-866ee7?style=for-the-badge&amp;logo=GitHub&amp;logoColor=333333&amp;labelColor=f9f9f9" alt="github.com"></a> +<a href="https://www.buymeacoffee.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/Buy%20me%20a%20coffee-dumindu-FFDD00?style=for-the-badge&amp;logo=buymeacoffee&amp;logoColor=333333&amp;labelColor=f9f9f9" alt="buymeacoffee"></a></p> +<h2 id="overview">Overview</h2> +<p>This publication has its origins in the posts I authored on Medium at <a href="https://medium.com/learning-rust" target="_blank" >https://medium.com/learning-rust</a>. However, please note that I have ceased updating the Medium posts. All current and future updates, new content, code, and grammar fixes will be exclusively maintained and released here, <a href="https://learning-rust.github.io" target="_blank" >https://learning-rust.github.io</a>.</p>Ownershiphttps://learning-rust.github.io/docs/ownership/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/ownership/<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// [1, 2, 3] [1, 2, 3] +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// Error; use of moved value: `a` +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>In the above examples, we are just trying to <strong>assign the value of <code>a</code> to <code>b</code></strong> . Almost the same code in both code blocks, but having <strong>two different data types</strong>. And the second one gives an error. This is because of the <strong>Ownership</strong>.</p>Panickinghttps://learning-rust.github.io/docs/panicking/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/panicking/<h2 id="panic">panic!()</h2> +<ul> +<li>In some cases, when an error occurs we can not do anything to handle it, <strong>if the error is something which should not have happened</strong>. In other words, if it’s an <strong>unrecoverable error</strong>.</li> +<li>Also <strong>when we are not using a feature-rich debugger or proper logs</strong>, sometimes we need to <strong>debug the code by quitting the program from a specific line of code</strong> by printing out a specific message or a value of a variable binding to understand the current flow of the program. +For above cases, we can use <code>panic!</code> macro.</li> +</ul> +<p>⭐ <code>panic!()</code> runs <strong>thread based</strong>. One thread can be panicked, while other threads are running.</p>Primitive Data Typeshttps://learning-rust.github.io/docs/primitive-data-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/primitive-data-types/<ul> +<li> +<h2 id="bool">bool</h2> +</li> +</ul> +<p>true or false</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">bool</span> <span class="o">=</span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ⭐️ no TRUE, FALSE, 1, 0 +</span></span></span></code></pre></div><ul> +<li> +<h2 id="char">char</h2> +</li> +</ul> +<p>A single Unicode scalar value</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">&#39;x&#39;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">char</span> <span class="o">=</span><span class="w"> </span><span class="sc">&#39;😎&#39;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ⭐️ no &#34;x&#34;, only single quotes +</span></span></span></code></pre></div><p>Because of Unicode support, char is not a single byte, but four(32 bits).</p> +<ul> +<li> +<h2 id="i8-i16-i32-i64-i128">i8, i16, i32, i64, i128</h2> +</li> +</ul> +<p>8, 16, 32, 64 and 128 bit fixed sized signed(+/-) integer types</p>Smart Compilerhttps://learning-rust.github.io/docs/smart-compiler/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/smart-compiler/<h2 id="why-compiler">Why Compiler?</h2> +<p>The Rust compiler does the most significant job to prevent errors in Rust programs. It <strong>analyzes the code at compile-time</strong> and issues warnings, if the code does not follow memory management rules or lifetime annotations correctly.</p> +<p>For example,</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[allow(unused_variables)]</span><span class="w"> </span><span class="c1">//πŸ’‘ A lint attribute used to suppress the warning; unused variable: `b` +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ------ Compile-time error ------ +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">error</span><span class="p">[</span><span class="n">E0382</span><span class="p">]</span>: <span class="nc">use</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">value</span>: <span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">-</span>-&gt; <span class="nc">src</span><span class="o">/</span><span class="n">main</span><span class="p">.</span><span class="n">rs</span>:<span class="mi">6</span>:<span class="mi">22</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">3</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">here</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">4</span><span class="w"> </span><span class="o">|</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">5</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">^</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">used</span><span class="w"> </span><span class="n">here</span><span class="w"> </span><span class="n">after</span><span class="w"> </span><span class="k">move</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">note</span>: <span class="nc">move</span><span class="w"> </span><span class="n">occurs</span><span class="w"> </span><span class="n">because</span><span class="w"> </span><span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w"> </span><span class="n">has</span><span class="w"> </span><span class="k">type</span> <span class="err">`</span><span class="n">std</span>::<span class="n">vec</span>::<span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">i32</span><span class="o">&gt;</span><span class="err">`</span><span class="p">,</span><span class="w"> </span><span class="n">which</span><span class="w"> </span><span class="n">does</span><span class="w"> </span><span class="n">not</span><span class="w"> </span><span class="n">implement</span><span class="w"> </span><span class="n">the</span><span class="w"> </span><span class="err">`</span><span class="nb">Copy</span><span class="err">`</span><span class="w"> </span><span class="k">trait</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">error</span>: <span class="nc">aborting</span><span class="w"> </span><span class="n">due</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">previous</span><span class="w"> </span><span class="n">error</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">For</span><span class="w"> </span><span class="n">more</span><span class="w"> </span><span class="n">information</span><span class="w"> </span><span class="n">about</span><span class="w"> </span><span class="n">this</span><span class="w"> </span><span class="n">error</span><span class="p">,</span><span class="w"> </span><span class="kr">try</span><span class="w"> </span><span class="err">`</span><span class="n">rustc</span><span class="w"> </span><span class="o">--</span><span class="n">explain</span><span class="w"> </span><span class="n">E0382</span><span class="err">`</span><span class="p">.</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ⭐ instead using #[allow(unused_variables)], consider using &#34;let _b = a;&#34; in line 4. +</span></span></span><span class="line"><span class="cl"><span class="c1">// Also you can use &#34;let _ =&#34; to completely ignore return values +</span></span></span></code></pre></div><blockquote> +<p>πŸ’­ In the previous sections, we have discussed memory management concepts like <a href="https://learning-rust.github.io/docs/ownership" >ownership</a>, <a href="https://learning-rust.github.io/docs/borrowing" >borrowing</a>, <a href="https://learning-rust.github.io/docs/lifetimes" >lifetimes</a> and etc.</p>STD, Primitives and Preludeshttps://learning-rust.github.io/docs/std-primitives-and-preludes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/std-primitives-and-preludes/<p>⭐️ In Rust, language elements are implemented by not only <strong><code>std</code> library</strong> crate but also <strong>compiler</strong> as well. Examples,</p> +<ul> +<li><strong><a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >Primitives</a></strong>: Defined by the compiler and methods are implemented by <code>std</code> library directly on primitives.</li> +<li><strong><a href="https://doc.rust-lang.org/std/#macros" target="_blank" >Standard Macros</a></strong>: Defined by both compiler and <code>std</code></li> +</ul> +<p>The <strong><code>std</code></strong> library has been divided into <strong><a href="https://doc.rust-lang.org/std/#modules" target="_blank" >modules</a></strong>, according to the main areas each covered.</p> +<p>⭐️ While primitives are implemented by the <strong>compiler</strong>, the standard library implements the <strong>most useful methods</strong> directly on the primitive types. But some <strong>rarely useful language elements</strong> of some primitives are stored on relevant <strong><code>std</code> modules</strong>. This is why you can see <code>char</code>, <code>str</code> and integer types on both <a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >primitives</a> and <a href="https://doc.rust-lang.org/std/#modules" target="_blank" ><code>std</code> modules</a>.</p>Structshttps://learning-rust.github.io/docs/structs/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/structs/<p>⭐️ Structs are used to <strong>encapsulate related properties</strong> into one unified data type.</p> +<p>πŸ’‘ By convention, the name of the struct should follow <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a>.</p> +<p>There are 3 variants of structs,</p> +<ol> +<li><strong>C-like structs</strong></li> +</ol> +<ul> +<li>One or more comma-separated name:value pairs</li> +<li>Brace-enclosed list</li> +<li>Similar to classes (without its methods) in OOP languages</li> +<li>Because fields have names, we can access them through dot notation</li> +</ul> +<ol start="2"> +<li><strong>Tuple structs</strong></li> +</ol> +<ul> +<li>One or more comma-separated values</li> +<li>A parenthesized list like tuples</li> +<li>Looks like a named tuples</li> +</ul> +<ol start="3"> +<li><strong>Unit structs</strong></li> +</ol> +<ul> +<li>A struct with no members at all</li> +<li>It defines a new type but it resembles an empty tuple, ()</li> +<li>Rarely in use, useful with generics</li> +</ul> +<p>⭐️ When regarding OOP in Rust, attributes and methods are placed separately on <strong>structs</strong> and <strong>traits</strong>. Structs contain only attributes, traits contain only methods. They are getting connected via <strong>impls</strong>.</p>Unwrap and Expecthttps://learning-rust.github.io/docs/unwrap-and-expect/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/unwrap-and-expect/<h2 id="unwrap">unwrap()</h2> +<ul> +<li>If an <code>Option</code> type has <strong><code>Some</code></strong> value or a <code>Result</code> type has a <strong><code>Ok</code></strong> value, <strong>the value inside them</strong> passes to the next step.</li> +<li>If the <code>Option</code> type has <strong><code>None</code></strong> value or the <code>Result</code> type has <strong><code>Err</code></strong> value, <strong>program panics</strong>; If <code>Err</code>, panics with the error message.</li> +</ul> +<p>The functionality is bit similar to the following codes, which are using <code>match</code> instead <code>unwrap()</code>.</p> +<p>Example with <code>Option</code> and <code>match</code>, before using <code>unwrap()</code></p>Usehttps://learning-rust.github.io/docs/use/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/use/<p>Let&rsquo;s see the main usages of the <code>use</code> keyword.</p> +<h2 id="01-bind-a-full-path-to-a-new-name">01. Bind a full path to a new name</h2> +<p>Mainly <code>use</code> keyword is used to bind a full path of an element to a new name. So the user doesn’t want to repeat the full path each time.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// -- Initial code without the `use` keyword -- +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> </span><span class="c1">// Using full path +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// -- Usage of the `use` keyword -- +</span></span></span><span class="line"><span class="cl"><span class="c1">// 01. Create an alias for module +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 02. Create an alias for module elements +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 03. Customize names with the `as` keyword +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="n">greet</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h2 id="02-import-elements-to-scope">02. Import elements to scope</h2> +<p>Another common usage of <code>use</code> is importing elements to scope. Remember that, this is also a bit similar to creating an alias and using it instead of using the full path.</p>Variable bindings, Constants & Staticshttps://learning-rust.github.io/docs/variable-bindings-constants-and-statics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/variable-bindings-constants-and-statics/<h2 id="variable-bindings-constants--statics">Variable bindings, Constants &amp; Statics</h2> +<p>⭐️ In Rust, variables are <strong>immutable by default</strong>, so we call them <strong>Variable bindings</strong>. To make them mutable, the <code>mut</code> keyword is used.</p> +<p>⭐️ Rust is a <strong>statically typed</strong> language; it checks data types at compile-time. But it <strong>doesn’t require you to actually type it when declaring variable bindings</strong>. In that case, the compiler checks the usage and sets a better data type for it. But for <strong>constants and statics, you must annotate the type</strong>. Types come after a colon(<code>:</code>).</p>Vectorshttps://learning-rust.github.io/docs/vectors/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/vectors/<p>If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of <strong>a re-sizable array</strong> but <strong>all elements must be in the same type</strong>.</p> +<p>⭐️ It’s a generic type, written as <strong><code>Vec&lt;T&gt;</code></strong>Β . T can have any type, ex. The type of a Vec of i32s is <code>Vec&lt;i32&gt;</code>. Also, Vectors always allocate their data in a dynamically allocated heap.</p>Why Rust?https://learning-rust.github.io/docs/why-rust/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/why-rust/<h2 id="history-of-rust">History of Rust</h2> +<p>Rust was initially designed and developed by former Mozilla employee <strong><a href="https://github.com/graydon" target="_blank" >Graydon Hoare</a></strong> as a personal project. Mozilla began sponsoring the project in 2009 and announced it in 2010. But the first stable release, Rust 1.0, was released on May 15, 2015.</p> +<p>Since Rust 1.0, major updates have been released as <a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#rust-editions" ><code>Editions</code></a> approximately every three years: Rust 2015 (with the release of Rust 1.0) , Rust 2018, Rust 2021, and Rust 2024, all maintaining backward compatibility.</p>Workspaceshttps://learning-rust.github.io/docs/workspaces/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/workspaces/<p>When the code base is getting larger, you might need to work with <strong>multiple crates on the same project</strong>. Rust supports this via Workspaces. You can <strong>analyze (<code>cargo check</code>), build, run tests or generate docs for all crates</strong> at once by running <code>cargo</code> commands from the project root.</p> +<p>⭐️ When working on multiple crates same time, there is a higher possibility of having shared dependencies on crates. To prevent downloading and compiling the same dependency multiple times, Rust uses a <strong>shared build directory</strong> under the project root, while running <code>cargo build</code> from the project root.</p> \ No newline at end of file diff --git a/docs/docs/installation/index.html b/docs/docs/installation/index.html new file mode 100644 index 0000000..ea90f9e --- /dev/null +++ b/docs/docs/installation/index.html @@ -0,0 +1,6 @@ +Installation Β· Learning Rust +

Installation

Rustup

There are many ways to install Rust on your system. For the moment the official way to install Rust is using Rustup.

πŸ“– Rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between stable, beta, and nightly compilers and keep them updated. It also makes cross-compiling simpler with binary builds of the standard library for common platforms.

πŸ“– Rustup installs rustc, cargo, rustup and other standard tools to Cargo’s bin directory. On Unix it is located at $HOME/.cargo/bin and on Windows at %USERPROFILE%\.cargo\bin. This is the same directory that cargo install will install Rust programs and Cargo plugins.

πŸ”Ž The main tools Rustup installs to the Cargo’s bin directory,

  • rustc: The Rust compiler.
  • cargo: The Rust’s built-in package manager and the build system.
  • rustup: The Rust toolchain installer.
  • rustfmt: The Rust’s official tool of formatting Rust code according to style guidelines.
  • cargo-fmt: Helps to run rustfmt on whole Rust projects, including multi-crate workspaces.
  • cargo-clippy: A lint tool that provides extra checks for common mistakes and stylistic choices.
  • cargo-miri:An experimental Rust interpreter, which can be used for checking for undefined-behavior.
  • rustdoc: A local copy of the Rust documentation.
  • rust-analyzer: A language server that provides support for editors and IDEs.
  • rust-gdb: A debugger that wraps GNU Debugger(GDB).

Installation

For Mac and Linux Users

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
+

For Windows Users

Download rustup-init.exe from www.rustup.rs and run.

πŸ’‘ You may need to install Visual C++ Build Tools 2019 or higher, which requires an additional 3–4 GBs.

πŸ‘¨β€πŸ« Before going to the next…

  • To verify the current Rust version, use the rustc --version or shorter formrustc -V command.
  • Rust follows six week release cycles. Use the rustup update command to update the Rust ecosystem.
  • You can access Rust’s offline documentation via the rustup doc command.
  • For a full list of rustup commands, refer to the rustup --help command.
\ No newline at end of file diff --git a/docs/docs/learning_rust_medium.png b/docs/docs/learning_rust_medium.png new file mode 100644 index 0000000..f2e7a46 Binary files /dev/null and b/docs/docs/learning_rust_medium.png differ diff --git a/docs/docs/lifetimes/index.html b/docs/docs/lifetimes/index.html new file mode 100644 index 0000000..a14f294 --- /dev/null +++ b/docs/docs/lifetimes/index.html @@ -0,0 +1,157 @@ +Lifetimes Β· Learning Rust +

Lifetimes

When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.

Think,

  • We have a variable binding, a.
  • We are referencing the value of a, from another variable binding x. +We have to make sure that a lives until we stop using x.

πŸ”Ž Memory management is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used Manual Memory Management which requires the programmer to give manual instructions to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented Garbage collection(GC), a form of Automatic Memory Management(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However Objective-C and Swift provide similar functionality through Automatic Reference Counting(ARC).

What is Lifetime?

In Rust,

  • A resource can only have one owner at a time. When it goes out of the scope, Rust removes it from the Memory.
  • When we want to reuse the same resource, we are referencing it/ borrowing its content.
  • When dealing with references, we have to specify lifetime annotations to provide instructions for the compiler to set how long those referenced resources should be alive.
  • ⭐ But because of lifetime annotations make the code more verbose, in order to make common patterns more ergonomic, Rust allows lifetimes to be elided/omitted in fn definitions. In this case, the compiler assigns lifetime annotations implicitly.

Lifetime annotations are checked at compile-time. Compiler checks when a data is used for the first and the last times. According to that, Rust manages memory in run time. This is the major reason for slower compilation times in Rust.

  • Unlike C and C++, usually, Rust doesn’t explicitly drop values at all.
  • Unlike GC, Rust doesn’t place deallocation calls where the data is no longer referenced.
  • Rust places deallocation calls where the data is about to go out of the scope and then enforces that no references to that resource exist after that point.

Usage

Lifetimes are denoted with an apostrophe. By convention, a lowercase letter is used for naming. Usually starts with 'a and follows alphabetic order when we need to add multiple lifetime annotations.

When using references,

01. On Function Declaration

  • Input and output parameters with references should attach lifetimes after the & sign. +ex. ..(x: &'a str) , ..(x: &'a mut str)

  • After the function name, we should mention that the given lifetimes are generic types. +ex. fn foo<'a>(..) , fn foo<'a, 'b>(..)

// No inputs, return a reference
+fn function<'a>() -> &'a str {}
+
+// Single input
+fn function<'a>(x: &'a str) {}
+
+// Single input and output, both have the same lifetime
+// The output should live at least as long as input exists
+fn function<'a>(x: &'a str) -> &'a str {}
+
+// Multiple inputs, only one input and the output share same lifetime
+// The output should live at least as long as y exists
+fn function<'a>(x: i32, y: &'a str) -> &'a str {}
+
+// Multiple inputs, both inputs and the output share same lifetime
+// The output should live at least as long as x and y exist
+fn function<'a>(x: &'a str, y: &'a str) -> &'a str {}
+
+// Multiple inputs, inputs can have different lifetimes πŸ”Ž
+// The output should live at least as long as x exists
+fn function<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {}
+

02. On Struct or Enum Declaration

  • Elements with references should attach lifetimes after the & sign.
  • After the name of the struct or enum, we should mention that the given lifetimes are generic types.
// Single element
+// Data of x should live at least as long as Struct exists
+struct Struct<'a> {
+    x: &'a str
+}
+
+// Multiple elements
+// Data of x and y should live at least as long as Struct exists
+struct Struct<'a> {
+    x: &'a str,
+    y: &'a str
+}
+
+
+// Variant with a single element
+// Data of the variant should live at least as long as Enum exists
+enum Enum<'a> {
+    Variant(&'a Type)
+}
+

03. With Impls and Traits

struct Struct<'a> {
+    x: &'a str
+}
+    impl<'a> Struct<'a> {
+        fn function<'a>(&self) -> &'a str {
+            self.x
+        }
+    }
+
+
+struct Struct<'a> {
+    x: &'a str,
+    y: &'a str
+}
+    impl<'a> Struct<'a> {
+        fn new(x: &'a str, y: &'a str) -> Struct<'a> { // No need to specify <'a> after new; impl already has it
+          Struct {
+              x : x,
+              y : y
+          }
+        }
+    }
+
+
+// πŸ”Ž
+impl<'a> Trait<'a> for Type
+impl<'a> Trait for Type<'a>
+

04. With Generic Types

// πŸ”Ž
+fn function<F>(f: F) where for<'a> F: FnOnce(&'a Type)
+struct Struct<F> where for<'a> F: FnOnce(&'a Type) { x: F }
+enum Enum<F> where for<'a> F: FnOnce(&'a Type) { Variant(F) }
+impl<F> Struct<F> where for<'a> F: FnOnce(&'a Type) { fn x(&self) -> &F { &self.x } }
+

Lifetime Elision

As I mentioned earlier, in order to make common patterns more ergonomic, Rust allows lifetimes to be elided/omitted. This process is called Lifetime Elision.

πŸ’‘ For the moment Rust supports Lifetime Elisions only on fn definitions. But in the future, it will support for impl headers as well.

Lifetime annotations of fn definitions can be elided
if its parameter list has either,

  • only one input parameter passes by reference.
  • a parameter with either &self or &mut self reference.
fn triple(x: &u64) -> u64 { // Only one input parameter passes by reference
+    x * 3
+}
+
+
+fn filter(x: u8, y: &str) -> &str { // Only one input parameter passes by reference
+    if x > 5 { y } else { "invalid inputs" }
+}
+
+
+struct Player<'a> {
+    id: u8,
+    name: &'a str
+}
+    impl<'a> Player<'a> { // So far Lifetime Elisions are allowed only on fn definitions. But in the future, they might support on impl headers as well.
+        fn new(id: u8, name: &str) -> Player { // Only one input parameter passes by reference
+            Player {
+                id : id,
+                name : name
+            }
+        }
+
+        fn heading_text(&self) -> String { // An fn definition with &self (or &mut self) reference
+            format!("{}: {}", self.id, self.name)
+        }
+    }
+
+fn main() {
+    let player1 = Player::new(1, "Serena Williams");
+    let player1_heading_text = player1.heading_text()
+    println!("{}", player1_heading_text);
+}
+

πŸ’‘ In the Lifetime Elision process of fn definitions,

  • Each parameter passed by reference has got a distinct lifetime annotation. +ex. ..(x: &str, y: &str) β†’ ..<'a, 'b>(x: &'a str, y: &'b str)
  • If the parameter list only has one parameter passed by reference, that lifetime is assigned to all elided lifetimes in the return values of that function. +ex. ..(x: i32, y: &str) -> &str β†’ ..<'a>(x: i32, y: &'a str) -> &'a str
  • Even if it has multiple parameters passed by reference, if one of them has &self or &mut self, the lifetime of self is assigned to all elided output lifetimes. +ex. impl Impl{ fn function(&self, x: &str) -> &str {} } β†’ +impl<'a> Impl<'a>{ fn function(&'a self, x: &'b str) -> &'a str {} }
  • For all other cases, we have to write lifetime annotations manually.

'static Annotations

'static lifetime annotation is a reserved lifetime annotation. These references are valid for the entire program. They are saved in the data segment of the binary and the data referred to will never go out of scope.

static N: i32 = 5; // A constant with 'static lifetime
+
+let a = "Hello, world."; // a: &'static str
+
+
+fn index() -> &'static str { // No need to mention <'static> ; fn index ΜΆ<ΜΆ'ΜΆsΜΆtΜΆaΜΆtΜΆiΜΆcΜΆ>ΜΆ 
+	"Hello, world!"
+}
+

Few more examples about the usage of Rust lifetimes.

fn greeting<'a>() -> &'a str {
+  "Hi!"
+}
+
+
+fn fullname<'a>(fname: &'a str, lname: &'a str) -> String {
+  format!("{} {}", fname, lname)
+}
+
+
+struct Person<'a> {
+    fname: &'a str,
+    lname: &'a str
+}
+  impl<'a> Person<'a> {
+      fn new(fname: &'a str, lname: &'a str) -> Person<'a> { // No need to specify <'a> after new; impl already has it
+          Person {
+              fname : fname,
+              lname : lname
+          }
+      }
+
+      fn fullname(&self) -> String {
+          format!("{} {}", self.fname , self.lname)
+      }
+  }
+
+fn main() {
+    let player = Person::new("Serena", "Williams");
+    let player_fullname = player.fullname();
+
+    println!("Player: {}", player_fullname);
+}
+
\ No newline at end of file diff --git a/docs/docs/modules/index.html b/docs/docs/modules/index.html new file mode 100644 index 0000000..6a18e65 --- /dev/null +++ b/docs/docs/modules/index.html @@ -0,0 +1,180 @@ +Modules Β· Learning Rust +

Modules

01. In the same file

Related code and data are grouped into a module and stored in the same file.

fn main() {
+   greetings::hello();
+}
+
+mod greetings {
+  // ⭐️ By default, everything inside a module is private
+  pub fn hello() { // ⭐️ So function has to be public to access from outside
+    println!("Hello, world!");
+  }
+}
+

Modules can also be nested.

fn main() { 
+  phrases::greetings::hello();
+}
+
+mod phrases { 
+  pub mod greetings { 
+    pub fn hello() { 
+      println!("Hello, world!");
+    }
+  }
+}
+

Private functions can be called from the same module or from a child module.

// 01. Calling private functions of the same module
+fn main() {
+  phrases::greet();
+}
+
+mod phrases {
+  pub fn greet() {
+    hello(); // Or `self::hello();`
+  }
+  
+  fn hello() {
+    println!("Hello, world!");
+  }
+}
+
+// 02. Calling private functions of the parent module
+fn main() {
+  phrases::greetings::hello();
+}
+
+mod phrases {
+  fn private_fn() {
+    println!("Hello, world!");
+  }
+  
+  pub mod greetings {
+    pub fn hello() {
+      super::private_fn();
+    }
+  }
+}
+

πŸ’‘ The self keyword is used to refer the same module, while the super keyword is used to refer parent module. Also, the super keyword can be used to access root functions from inside a module.

fn main() {
+  greetings::hello();
+}
+
+fn hello() {
+  println!("Hello, world!");
+}
+
+mod greetings {
+  pub fn hello() {
+    super::hello();
+  }
+}
+

πŸ”Ž When writing tests it’s a good practice to write tests inside a test module because they compile only when running tests.

fn greet() -> String {
+    "Hello, world!".to_string()
+}
+
+#[cfg(test)] // Only compiles when running tests
+mod tests {
+    use super::greet; // Import root greet function
+
+    #[test]
+    fn test_greet() {
+        assert_eq!("Hello, world!", greet());
+    }
+}
+

02. In a different file, same directory

// ↳ main.rs
+mod greetings; // Import greetings module
+
+fn main() {
+  greetings::hello();
+}
+
+// ↳ greetings.rs
+// ⭐️ No need to wrap the code with a mod declaration. The file itself acts as a module.
+pub fn hello() { // The function has to be public to access from outside
+  println!("Hello, world!");
+}
+

If we wrap file content with a mod declaration, it will act as a nested module.

// ↳ main.rs
+mod phrases;
+
+fn main() {
+  phrases::greetings::hello();
+}
+
+// ↳ phrases.rs
+pub mod greetings { // ⭐️ The module has to be public to access from outside
+  pub fn hello() {
+    println!("Hello, world!");
+  }
+}
+

03. In a different file, different directory

mod.rs in the directory module root is the entry point to the directory module. All other files in that directory root, act as sub-modules of the directory module.

// ↳ main.rs
+mod greetings;
+
+fn main() {
+  greetings::hello();
+}
+
+// ↳ greetings/mod.rs
+pub fn hello() { // ⭐️ The function has to be public to access from outside
+  println!("Hello, world!");
+}
+

Again, If we wrap file content with a mod declaration, it will act as a nested module.

// ↳ main.rs
+mod phrases;
+
+fn main() {
+  phrases::greetings::hello();
+}
+
+// ↳ phrases/mod.rs
+pub mod greetings { // ⭐️ The module has to be public to access from outside
+  pub fn hello() {
+    println!("Hello, world!");
+  }
+}
+

Other files in the directory module act as sub-modules for mod.rs.

// ↳ main.rs
+mod phrases;
+
+fn main() {
+  phrases::hello()
+}
+
+// ↳ phrases/mod.rs
+mod greetings;
+
+pub fn hello() {
+  greetings::hello()
+}
+
+// ↳ phrases/greetings.rs
+pub fn hello() {
+  println!("Hello, world!");
+}
+

⭐️ If you need to access an element of phrases/greetings.rs from outside the module, you have to import the greetings module as a public module.

// ↳ main.rs
+mod phrases;
+
+fn main() {
+    phrases::greetings::hello();
+}
+
+// ↳ phrases/mod.rs
+pub mod greetings;  // ⭐️ `pub mod` instead `mod`
+
+// ↳ phrases/greetings.rs
+pub fn hello() {
+  println!("Hello, world!");
+}
+

πŸ”Ž It’s unable to import child file modules of directory modules to main.rs, so you can’t use mod phrases::greetings; from main.rs. But there is a way to import phrases::greetings::hello() to phrases module by re-exporting hello to phrases module. So you can call it directly as phrases::hello().

// ↳ phrases/greetings.rs
+pub fn hello() {
+  println!("Hello, world!");
+}
+
+// ↳ phrases/mod.rs
+pub mod greetings;
+
+pub use self::greetings::hello; // Re-export `greetings::hello` to phrases
+
+// ↳ main.rs
+mod phrases;
+
+fn main() {
+    phrases::hello(); // You can call `hello()` directly from phrases
+}
+

This allows you to present an external interface that may not directly map to your internal code organization. If still it is not clear, don’t worry; We discuss the usages of use on an upcoming section in this post.

\ No newline at end of file diff --git a/docs/docs/operators/index.html b/docs/docs/operators/index.html new file mode 100644 index 0000000..f40bdfe --- /dev/null +++ b/docs/docs/operators/index.html @@ -0,0 +1,70 @@ +Operators Β· Learning Rust +

Operators

  • Arithmetic Operators

+ - * / %

let a = 5;
+let b = a + 1; //6
+let c = a - 1; //4
+let d = a * 2; //10
+let e = a / 2; // ⭐️ 2 not 2.5
+let f = a % 2; //1
+
+let g = 5.0 / 2.0; //2.5
+
  • Comparison Operators

== != < > <= >=

let a = 1;
+let b = 2;
+
+let c = a == b; //false
+let d = a != b; //true
+let e = a < b; //true
+let f = a > b; //false
+let g = a <= a; //true
+let h = a >= a; //true
+
+// πŸ”Ž
+let i = true > false; //true
+let j = 'a' > 'A'; //true
+
  • Logical Operators

! && ||

let a = true;
+let b = false;
+
+let c = !a; //false
+let d = a && b; //false
+let e = a || b; //true
+

πŸ”Ž On integer types,! inverts the individual bits in the two’s complement representation of the value.

let a = !-2; //1
+let b = !-1; //0
+let c = !0; //-1
+let d = !1; //-2
+
  • Bitwise Operators

& | ^ << >>

let a = 1;
+let b = 2;
+
+let c = a & b;  //0  (01 && 10 -> 00)
+let d = a | b;  //3  (01 || 10 -> 11)
+let e = a ^ b;  //3  (01 != 10 -> 11)
+let f = a << b; //4  (Add b number of 0s to the end of a -> '01'+'00' -> 100)
+let g = a >> b; //0  (Remove b number of bits from the end of a -> oΜΆ1ΜΆ -> 0)
+
  • Assignment and Compound Assignment Operators

The = operator is used to assign a name to a value or a function. Compound Assignment Operators are created by composing one of + - * / % & | ^ << >> operators with = operator.

let mut a = 2;
+
+a += 5; //2 + 5 = 7
+a -= 2; //7 - 2 = 5
+a *= 5; //5 * 5 = 25
+a /= 2; //25 / 2 = 12 not 12.5
+a %= 5; //12 % 5 = 2
+
+a &= 2; //10 && 10 -> 10 -> 2
+a |= 5; //010 || 101 -> 111 -> 7
+a ^= 2; //111 != 010 -> 101 -> 5
+a <<= 1; //'101'+'0' -> 1010 -> 10
+a >>= 2; //101ΜΆ0ΜΆ -> 10 -> 2
+
  • Type Casting Operator

as

let a = 15;
+let b = (a as f64) / 2.0; //7.5
+
  • Borrowing and Dereference Operators

& &mut *

πŸ”Ž The & or &mut operators are used for borrowing and * operator for dereferencing. For more information, refer Ownership, Borrowing & Lifetimes sections.

πŸ‘¨β€πŸ« Before going to the next…

  • About string concatenation,
let (s1, s2) = ("some", "thing"); // both &str
+// All bellow codes return `String`; something
+
+let s = String::from(s1) + s2; // String + &str
+
+let mut s = String::from(s1); // String
+s.push_str(s2); // + &str
+
+let s = format!("{}{}", s1, s2); // &str/String + &str/String
+
+let s = [s1, s2].concat(); // &str or String array
+
\ No newline at end of file diff --git a/docs/docs/option-and-result/index.html b/docs/docs/option-and-result/index.html new file mode 100644 index 0000000..0282dc5 --- /dev/null +++ b/docs/docs/option-and-result/index.html @@ -0,0 +1,87 @@ +Option and Result Β· Learning Rust +

Option and Result

Why Option and Result?

Many languages use null\ nil\ undefined types to represent empty outputs, and Exceptions to handle errors. Rust skips using both, especially to prevent issues like null pointer exceptions, sensitive data leakages through exceptions, etc. Instead, Rust provides two special generic enums;Option and Result to deal with above cases.

πŸ’­ In the previous sections, we have discussed about the basics of enums, generics and Result & Option types.

As you know,

  • An optional value can have either Some value or no value/ None.
  • A result can represent either success/ Ok or failure/ Err
// An output can have either Some value or no value/ None.
+enum Option<T> { // T is a generic and it can contain any type of value.
+    Some(T),
+    None,
+}
+
+// A result can represent either success/ Ok or failure/ Err.
+enum Result<T, E> { // T and E are generics. T can contain any type of value, E can be any error.
+    Ok(T),
+    Err(E),
+}
+

πŸ’­ Also as we discussed in preludes, not only Option and Result, and also their variants are in preludes. So, we can use them directly without using namespaces in the code.

Basic usages of Option

When writing a function or data type,

  • if an argument of the function is optional,
  • if the function is non-void and if the output it returns can be empty,
  • if the value of a property of the data type can be empty,

we have to use their data type as an Option type.

For example, if the function outputs a &str value and the output can be empty, the return type of the function should be set as Option<&str>.

fn get_an_optional_value() -> Option<&str> {
+
+    //if the optional value is not empty
+    return Some("Some value");
+    
+    //else
+    None
+}
+

In the same way, if the value of a property of a data type can be empty or optional like the middle_name of the Name data type in the following example, we should set its data type as an Option type.

struct Name {
+  first_name: String,
+  middle_name: Option<String>, // middle_name can be empty
+  last_name: String,
+}
+

πŸ’­ As you know, we can use pattern matching to catch the relevant return type (Some/ None) via match. There is a function in std::env called home_dir() to get the current user’s home directory. However, not all users have a home directory in systems like Linux, so the home directory of a user can be optional. So it returns an Option type; Option<PathBuf>.

use std::env;
+
+fn main() {
+    let home_path = env::home_dir();
+    match home_path {
+        Some(p) => println!("{:?}", p), // This prints "/root", if you run this in Rust playground
+        None => println!("Can not find the home directory!"),
+    }
+}
+

⭐ However, when using optional arguments with functions, we have to pass None values for empty arguments while calling the function.

fn get_full_name(fname: &str, lname: &str, mname: Option<&str>) -> String { // middle name can be empty
+  match mname {
+    Some(n) => format!("{} {} {}", fname, n, lname),
+    None => format!("{} {}", fname, lname),
+  }
+}
+
+fn main() {
+  println!("{}", get_full_name("Galileo", "Galilei", None));
+  println!("{}", get_full_name("Leonardo", "Vinci", Some("Da")));
+}
+
+// πŸ’‘ Better create a struct as Person with fname, lname, mname fields and create a impl function as full_name()
+

πŸ”Ž Other than that, Option types are used with nullable pointers in Rust. Because there are no null pointers in Rust, the pointer types should point to a valid location. So if a pointer can be nullable, we have use Option<Box<T>>Β .

Basic usages of Result

If a function can produce an error, we have to use a Result type by combining the data type of the valid output and the data type of the error. For example, if the data type of the valid output is u64 and error type is String, the return type should be Result<u64, String>.

fn function_with_error() -> Result<u64, String> {
+  
+    //if error happens
+    return Err("The error message".to_string());
+
+    // else, return valid output
+    Ok(255)
+}
+

πŸ’­ As you know, we can use the pattern matching to catch the relevant return types (Ok/Err) via match. There is a function to fetch the value of any environment variable in std::env called var(). Its input is the environment variable name. This can produce an error if we pass a wrong environment variable or the program cannot extract the value of the environment variable while running. So, its return type is a Result type; Result<String, VarError>.

use std::env;
+
+fn main() {
+    let key = "HOME";
+    match env::var(key) {
+        Ok(v) => println!("{}", v), // This prints "/root", if you run this in Rust playground
+        Err(e) => println!("{}", e), // This prints "environment variable not found", if you give a nonexistent environment variable
+    }
+}
+

is_some(), is_none(), is_ok(), is_err()

Other than match expressions, Rust provides is_some() , is_none() and is_ok() , is_err() functions to identify the return type.

fn main() {
+    let x: Option<&str> = Some("Hello, world!");
+    assert_eq!(x.is_some(), true);
+    assert_eq!(x.is_none(), false);
+
+    let y: Result<i8, &str> = Ok(10);
+    assert_eq!(y.is_ok(), true);
+    assert_eq!(y.is_err(), false);
+}
+

ok(), err() for Result types

In addition to that, Rust provides ok() and err() for Result types. They convert the Ok<T> and Err<E> values of a Result type to Option types.

fn main() {
+    let o: Result<i8, &str> = Ok(8);
+    let e: Result<i8, &str> = Err("message");
+    
+    assert_eq!(o.ok(), Some(8)); // Ok(v) ok = Some(v)
+    assert_eq!(e.ok(), None);    // Err(v) ok = None
+    
+    assert_eq!(o.err(), None);            // Ok(v) err = None
+    assert_eq!(e.err(), Some("message")); // Err(v) err = Some(v)
+}
+
\ No newline at end of file diff --git a/docs/docs/overview/index.html b/docs/docs/overview/index.html new file mode 100644 index 0000000..e01c571 --- /dev/null +++ b/docs/docs/overview/index.html @@ -0,0 +1,7 @@ +Overview Β· Learning Rust +

Overview

About me

πŸ§‘β€πŸ’» I am an expat working in Singapore as a Go Backend and DevOps Engineer. Feel free to reach out if you find any mistakes or anything that needs to be changed, including spelling or grammar errors. Alternatively, you can create a pull request, open an issue, or share your awesome ideas in this gist. Good luck with learning Rust!

learning-rust.github.io +learning-cloud-native-go.github.io

github.com +buymeacoffee

Overview

This publication has its origins in the posts I authored on Medium at https://medium.com/learning-rust. However, please note that I have ceased updating the Medium posts. All current and future updates, new content, code, and grammar fixes will be exclusively maintained and released here, https://learning-rust.github.io.

Learning Rust @Medium

\ No newline at end of file diff --git a/docs/docs/ownership/index.html b/docs/docs/ownership/index.html new file mode 100644 index 0000000..18745fe --- /dev/null +++ b/docs/docs/ownership/index.html @@ -0,0 +1,16 @@ +Ownership Β· Learning Rust +

Ownership

fn main() {
+    let a = [1, 2, 3];
+    let b = a;
+    println!("{:?} {:?}", a, b); // [1, 2, 3] [1, 2, 3]
+}
+
+fn main() {
+    let a = vec![1, 2, 3];
+    let b = a;
+    println!("{:?} {:?}", a, b); // Error; use of moved value: `a`
+}
+

In the above examples, we are just trying to assign the value of a to b . Almost the same code in both code blocks, but having two different data types. And the second one gives an error. This is because of the Ownership.

What is ownership?

⭐️ Variable bindings have ownership of what they’re bound to. A piece of data can only have one owner at a time. When a binding goes out of scope, Rust will free the bound resources. This is how Rust achieves memory safety.

Ownership (noun)
The act, state, or right of possessing something.

Copy types & move types

⭐️ When assigning a variable binding to another variable binding or when passing it to a function(Without referencing), if its data type is a

  1. Copy Type

    • Bound resources are made a copy and assign or pass it to the function.
    • The ownership state of the original bindings is set to β€œcopied” state.
    • Mostly Primitive types
  2. Move type

    • Bound resources are moved to the new variable binding and we can not access the original variable binding anymore.
    • The ownership state of the original bindings is set to β€œmoved” state.
    • Non-primitive types

πŸ”Ž The functionality of a type is handled by the traits which have been implemented to it. By default, variable bindings have β€˜move semantics.’ However, if a type implements core::marker::Copy trait , it has a ‘copy semantics’.

πŸ’‘ So in the above second example, ownership of the Vec object moves to b and a doesn’t have any ownership to access the resource.

\ No newline at end of file diff --git a/docs/docs/panicking/index.html b/docs/docs/panicking/index.html new file mode 100644 index 0000000..b95d6bf --- /dev/null +++ b/docs/docs/panicking/index.html @@ -0,0 +1,147 @@ +Panicking Β· Learning Rust +

Panicking

panic!()

  • In some cases, when an error occurs we can not do anything to handle it, if the error is something which should not have happened. In other words, if it’s an unrecoverable error.
  • Also when we are not using a feature-rich debugger or proper logs, sometimes we need to debug the code by quitting the program from a specific line of code by printing out a specific message or a value of a variable binding to understand the current flow of the program. +For above cases, we can use panic! macro.

⭐ panic!() runs thread based. One thread can be panicked, while other threads are running.

01. Quit from a specific line.

fn main() {
+    // some code
+
+    // if we need to debug in here
+    panic!();
+}
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'explicit panic', src/main.rs:5:5
+

02. Quit with a custom error message.

#[allow(unused_mut)] // πŸ’‘ A lint attribute used to suppress the warning; username variable does not need to be mutable
+fn main() {
+    let mut username = String::new();
+
+    // some code to get the name
+  
+    if username.is_empty() {
+        panic!("Username is empty!");
+    }
+
+    println!("{}", username);
+}
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'Username is empty!', src/main.rs:8:9
+

03. Quit with the value of code elements.

#[derive(Debug)] // πŸ’‘ A lint attribute which use to implement `std::fmt::Debug` to Color
+struct Color {
+    r: u8,
+    g: u8,
+    b: u8,
+}
+
+#[allow(unreachable_code)] // πŸ’‘ A lint attribute used to suppress the warning; unreachable statement
+fn main() {
+    let some_color: Color;
+    
+    // some code to get the color. ex
+    some_color = Color {r: 255, g: 255, b: 0};
+
+    // if we need to debug in here
+    panic!("{:?}", some_color);
+
+    println!(
+        "The color = rgb({},{},{})",
+        some_color.r, some_color.g, some_color.b
+    );
+}
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'Color { r: 255, g: 255, b: 0 }', src/main.rs:16:5
+

As you can see in the above examples panic!() supports println!() type style arguments. By default, it prints the error message, file path and line & column numbers where the error happens.

unimplemented!()

πŸ’‘ If your code is having unfinished code sections, there is a standardized macro as unimplemented!() to mark those routes. The program will be panicked with a β€œnot yet implemented” error message, if the program runs through those routes.

// error messages with panic!()
+thread 'main' panicked at 'explicit panic', src/main.rs:6:5
+thread 'main' panicked at 'Username is empty!', src/main.rs:9:9
+thread 'main' panicked at 'Color { r: 255, g: 255, b: 0 }', src/main.rs:17:5
+
+// error messages with unimplemented!()
+thread 'main' panicked at 'not yet implemented', src/main.rs:6:5
+thread 'main' panicked at 'not yet implemented: Username is empty!', src/main.rs:9:9
+thread 'main' panicked at 'not yet implemented: Color { r: 255, g: 255, b: 0 }', src/main.rs:17:5
+

unreachable!()

This is the standard macro to mark routes that the program should not enter. The program will be panicked with a β€œ‘internal error: entered unreachable code’” error message, if the program entered those routes.

fn main() {
+    let level = 22;
+    let stage = match level {
+        1..=5 => "beginner",
+        6..=10 => "intermediate",
+        11..=20 => "expert",
+        _ => unreachable!(),
+    };
+    
+    println!("{}", stage);
+}
+
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'internal error: entered unreachable code', src/main.rs:7:20
+

We can set custom error messages for this as well.

// --- with a custom message ---
+_ => unreachable!("Custom message"),
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'internal error: entered unreachable code: Custom message', src/main.rs:7:20
+
+
+// --- with debug data ---
+_ => unreachable!("level is {}", level),
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'internal error: entered unreachable code: level is 22', src/main.rs:7:14
+

assert!(), assert_eq!(), assert_ne!()

These are standard macros which usually use with test assertions.

  • assert!() ensures that a boolean expression is true. It panics if the expression is false.
fn main() {
+    let f = false;
+    
+    assert!(f)
+}
+
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'assertion failed: f', src/main.rs:4:5
+
  • assert_eq!() ensures that two expressions are equal. It panics if the expressions are not equal.
fn main() {
+    let a = 10;
+    let b = 20;
+    
+    assert_eq!(a, b);
+}
+
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'assertion failed: `(left == right)`
+  left: `10`,
+ right: `20`', src/main.rs:5:5
+
  • assert_ne!() ensures that two expressions are not equal. It panics if the expressions are equal.
fn main() {
+    let a = 10;
+    let b = 10;
+    
+    assert_ne!(a, b);
+}
+
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'assertion failed: `(left != right)`
+  left: `10`,
+ right: `10`', src/main.rs:5:5
+

⭐ Expressions which use with assert_eq!() and assert_ne!() should return same data type.

We can set custom error messages for these macros as well. For examples,

  1. With a custom message for assert_eq!()
fn main() {
+    let a = 10;
+    let b = 20;
+    
+    assert_eq!(a, b, "a and b should be equal");
+}
+
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'assertion failed: `(left == right)`
+  left: `10`,
+ right: `20`: a and b should be equal', src/main.rs:5:5
+
  1. assert_eq!() with debug data
fn main() {
+    let a = 10;
+    let b = 20;
+
+    let c = 40;
+    
+    assert_eq!(a+b, c, "a = {} ; b = {}", a, b);
+}
+
+// -------------- Compile-time error --------------
+thread 'main' panicked at 'assertion failed: `(left == right)`
+  left: `30`,
+ right: `40`: a = 10 ; b = 20', src/main.rs:7:5
+

debug_assert!(), debug_assert_eq!(), debug_assert_ne!()

πŸ”Ž These are similar to above assert macros. But these statements are only enabled in non optimized builds by default. All these debug_assert macros will be omitted in release builds, unless we pass -C debug-assertions to the compiler.

\ No newline at end of file diff --git a/docs/docs/primitive-data-types/index.html b/docs/docs/primitive-data-types/index.html new file mode 100644 index 0000000..2b5bd74 --- /dev/null +++ b/docs/docs/primitive-data-types/index.html @@ -0,0 +1,91 @@ +Primitive Data Types Β· Learning Rust +

Primitive Data Types

  • bool

true or false

let x = true;
+let y: bool = false;
+
+// ⭐️ no TRUE, FALSE, 1, 0
+
  • char

A single Unicode scalar value

let x = 'x';
+let y: char = '😎';
+
+// ⭐️ no "x", only single quotes
+

Because of Unicode support, char is not a single byte, but four(32 bits).

  • i8, i16, i32, i64, i128

8, 16, 32, 64 and 128 bit fixed sized signed(+/-) integer types

DATA TYPEMINMAX
i8-128127
i16-3276832767
i32-21474836482147483647
i64-92233720368547758089223372036854775807
i128-170141183460469231731687303715884105728170141183460469231731687303715884105727

πŸ’‘ The min and max values are based on the following equation; from -(2ⁿ⁻¹) to 2ⁿ⁻¹-1. You can use min_value() and max_value() functions to find min and max of each integer type. ex.i8::min_value();

let x = 10; // ⭐️ The default integer type in Rust is i32
+let y: i8 = -128;
+
  • u8, u16, u32, u64, u128

8, 16, 32, 64 and 128 bit fixed sized unsigned(0/+) integer types

DATA TYPEMINMAX
u80255
u16065535
u3204294967295
u64018446744073709551615
u1280340282366920938463463374607431768211455

πŸ’‘ The min and max values are based on the following equation; from 0 to 2ⁿ-1. Same way you can use min_value() and max_value() functions to find min and max of each integer type. ex.u8::max_value();

  • isize, usize

Pointer sized signed and unsigned integer types

The actual bit size depends on the computer architecture you are compiling your program for. By default, the sizes are equal to 32 bits on 32-bit platforms and 64 bits on 64-bit platforms.

πŸ”Ž Search more about cross-compiling and supported tiers of Rust programs.

  • f32, f64

32 and 64 bit sized floating point numbers(numbers with decimal points)

Rust follows IEEE Standard for Binary Floating-Point Arithmetic. The f32 type is similar to float(Single precision) in other languages, while f64 is similar to double(Double precision) in other languages.

let x = 1.5; // ⭐️ The default float type in Rust is f64
+let y: f64 = 2.0;
+

πŸ’‘ Should avoid using f32, unless you need to reduce memory consumption badly or if you are doing low-level optimization, when targeted hardware does not support for double-precision or when single-precision is faster than double-precision on it.

  • Array

Fixed size list of elements of same data type

let a = [1, 2, 3];
+let a: [i32; 3] = [1, 2, 3]; // [Type; NO of elements]
+
+let b: [i32; 0] = []; // An empty array
+
+let mut c: [i32; 3] = [1, 2, 3];
+c[0] = 2;
+c[1] = 4;
+c[2] = 6;
+
+println!("{:?}", c); // [2, 4, 6]
+println!("{:#?}", c);
+//  [
+//      2,
+//      4,
+//      6,
+//  ]
+
+let d = [0; 5];   // [0, 0, 0, 0, 0]
+let e = ["x"; 5]; // ["x", "x", "x", "x", "x"]
+

⭐️ Arrays are immutable by default and even with mut, its element count cannot be changed.

πŸ”Ž If you are looking for a dynamic/ growable array, you can use vectors. Vectors can contain any type of elements but all elements must be in the same data type.

  • Tuple

Fixed size ordered list of elements of different(or same) data types

let a = (1, 1.5, true, 'a');
+let a: (i32, f64, bool, char) = (1, 1.5, true, 'a');
+
+let mut b = (1, 1.5);
+b.0 = 2;
+b.1 = 3.0;
+
+println!("{:?}", b); // (2, 3.0)
+println!("{:#?}", b);
+// (
+//   2,
+//   3.0,
+// )
+
+let (c, d) = b; // c = 2, d = 3.0
+let (e, _, _, f) = a; // e = 1, f = 'a'
+
+let g = (0,); // single-element tuple
+let h = (b, (2, 4), 5); // ((2, 3.0), (2, 4), 5)
+

⭐️ Tuples are also immutable by default and even with mut, its element count cannot be changed. Also, if you want to change an element’s value, the new value should have the same data type of previous value.

  • Slice

Dynamically-sized reference to another data structure

Imagine you want to get/ pass a part of an array or any other data structure. Instead of copying it to another array (or same data structure), Rust allows for creating a view/ reference to access only that part of the data. This view/ reference can be mutable or immutable.

let a: [i32; 4] = [1, 2, 3, 4]; // Parent Array
+
+let b: &[i32] = &a; // Slicing whole array
+let c = &a[0..4]; // From 0th position to 4th(excluding)
+let d = &a[..]; // Slicing whole array
+
+let e = &a[1..3]; // [2, 3]
+let f = &a[1..]; // [2, 3, 4]
+let g = &a[..3]; // [1, 2, 3]
+
  • str

Unsized UTF-8 sequence of Unicode string slices

let a = "Hello, world."; // a: &'static str
+let b: &str = "こんにけは, δΈ–η•Œ!";
+

⭐️ It’s an immutable/ statically allocated slice holding an unknown sized sequence of UTF-8 code points stored in somewhere in memory. &str is used to borrow and assign the whole array to the given variable binding.

  • Function

As we discussed in the functions section as well, p1 is a function pointer to plus_one() in the following code.

fn main() {
+    let p1: fn(i32) -> i32 = plus_one;
+    let x = p1(5); // 6
+}
+
+fn plus_one(a: i32) -> i32 {
+    a + 1
+}
+

πŸ‘¨β€πŸ« Before going to the next…

  • In Rust, the default integer type is i32 and the default float type is f64.
let i = 10;   // Equals to `let i: i32 = 10;`
+let f = 3.14; // Equals to `let f: f64 = 3.14;`
+
  • Other than adding the type annotations to the variables, for numeric types, we can append the data type directly to the value as the suffix. Also, to improve the readability of long numbers, we can use _ as a divider.
let a = 5i8; // Equals to `let a: i8 = 5;`
+
+let b = 100_000_000; // Equals to `let b = 100000000;`
+// πŸ’‘ The placements of _s are not strict. ex. 10000_0000 is also valid.
+
+let pi = 3.141_592_653_59f64; // Equals to `let pi: f64 = 3.14159265359`
+
+const PI: f64 = 3.141_592_653_59; // In the constants and statics, the data type must be annotated in the beginning.
+
  • There are several string types in Rust. The String type is a heap-allocated string. This string is growable and is also guaranteed to be UTF-8. In general, you should use String when you need ownership, and &str when you just need to borrow a string.

  • A String type can be generated from a &str type, via the to_string() or String::from() methods. With as_str() method, a String type can be converted to a &str type.

let s: &str = "Hello"; // &str
+
+let s = s.to_string(); // String
+let s = String::from(s); // String
+
+let s = s.as_str(); // &str
+
\ No newline at end of file diff --git a/docs/docs/rust_playground.png b/docs/docs/rust_playground.png new file mode 100644 index 0000000..580f004 Binary files /dev/null and b/docs/docs/rust_playground.png differ diff --git a/docs/docs/smart-compiler/index.html b/docs/docs/smart-compiler/index.html new file mode 100644 index 0000000..10667b9 --- /dev/null +++ b/docs/docs/smart-compiler/index.html @@ -0,0 +1,82 @@ +Smart Compiler Β· Learning Rust +

Smart Compiler

Why Compiler?

The Rust compiler does the most significant job to prevent errors in Rust programs. It analyzes the code at compile-time and issues warnings, if the code does not follow memory management rules or lifetime annotations correctly.

For example,

#[allow(unused_variables)] //πŸ’‘ A lint attribute used to suppress the warning; unused variable: `b`
+fn main() {
+    let a = vec![1, 2, 3];
+    let b = a;
+
+    println!("{:?}", a);
+}
+
+
+// ------ Compile-time error ------
+error[E0382]: use of moved value: `a`
+ --> src/main.rs:6:22
+  |
+3 |     let b = a;
+  |         - value moved here
+4 |
+5 |     println!("{:?}", a);
+  |                      ^ value used here after move
+  |
+  = note: move occurs because `a` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
+
+error: aborting due to previous error
+For more information about this error, try `rustc --explain E0382`.
+
+// ⭐ instead using #[allow(unused_variables)], consider using "let _b = a;" in line 4. 
+// Also you can use "let _ =" to completely ignore return values
+

πŸ’­ In the previous sections, we have discussed memory management concepts like ownership, borrowing, lifetimes and etc.

Rust compiler checks not only issues related with lifetimes or memory management and also common coding mistakes, like the following code.

struct Color {
+    r: u8,
+    g: u8,
+    b: u8,
+}
+
+fn main() {
+    let yellow = Color {
+        r: 255,
+        g: 255,
+        d: 0,
+    };
+
+    println!("Yellow = rgb({},{},{})", yellow.r, yellow.g, yellow.b);
+}
+
+
+// ------------ Compile-time error ------------
+error[E0560]: struct `Color` has no field named `d`
+  --> src/main.rs:11:9
+   |
+11 |         d: 0,
+   |         ^ field does not exist - did you mean `b`?
+
+error: aborting due to previous error
+For more information about this error, try `rustc --explain E0560`.
+

Explain Error Codes

Above error messages are very descriptive and we can easily see where is the error. But while we can not identify the issue via the error message, rustc --explain commands help us to identify the error type and how to solve it, by showing simple code samples which express the same problem and the solution we have to use.

For example, rustc --explain E0571 shows the following output in the console.

A `break` statement with an argument appeared in a non-`loop` loop.
+
+Example of erroneous code:
+ο½€ο½€ο½€
+let result = while true {
+    if satisfied(i) {
+        break 2*i; // error: `break` with value from a `while` loop
+    }
+    i += 1;
+};
+ο½€ο½€ο½€
+
+The `break` statement can take an argument (which will be the value of the loop
+expression if the `break` statement is executed) in `loop` loops, but not
+`for`, `while`, or `while let` loops.
+
+Make sure `break value;` statements only occur in `loop` loops:
+ο½€ο½€ο½€
+let result = loop { // ok!
+    if satisfied(i) {
+        break 2*i;
+    }
+    i += 1;
+};
+ο½€ο½€ο½€
+

πŸ’‘ Also you can read the same explanations via Rust Compiler Error Index. For example to check the explanation of E0571 error, you can use https://doc.rust-lang.org/error-index.html#E0571.

\ No newline at end of file diff --git a/docs/docs/std-primitives-and-preludes/index.html b/docs/docs/std-primitives-and-preludes/index.html new file mode 100644 index 0000000..7ae4ba8 --- /dev/null +++ b/docs/docs/std-primitives-and-preludes/index.html @@ -0,0 +1,93 @@ +STD, Primitives and Preludes Β· Learning Rust +

STD, Primitives and Preludes

⭐️ In Rust, language elements are implemented by not only std library crate but also compiler as well. Examples,

  • Primitives: Defined by the compiler and methods are implemented by std library directly on primitives.
  • Standard Macros: Defined by both compiler and std

The std library has been divided into modules, according to the main areas each covered.

⭐️ While primitives are implemented by the compiler, the standard library implements the most useful methods directly on the primitive types. But some rarely useful language elements of some primitives are stored on relevant std modules. This is why you can see char, str and integer types on both primitives and std modules.

Primitives

// Primitives: Defined by the compiler and methods are directly implemented by std
+bool, char, slice, str
+
+i8, i16, i32, i64, i128, isize
+u8, u16, u32, u64, u128, usize
+
+f32, f64
+
+array, tuple
+
+pointer, fn, reference
+

Standard Macros

// Standard Macros also defined by both compiler and std
+print, println, eprint, eprintln
+format, format_args
+write, writeln
+
+concat, concat_idents, stringify // concat_idents: nightly-only experimental API
+
+include, include_bytes, include_str
+
+assert, assert_eq, assert_ne
+debug_assert, debug_assert_eq, debug_assert_ne
+
+try, panic, compile_error, unreachable, unimplemented
+
+file, line, column, module_path
+env, option_env
+cfg
+
+select, thread_local // select: nightly-only experimental API
+
+vec
+

Std Modules

// std modules
+char, str
+
+i8, i16, i32, i64, i128, isize
+u8, u16, u32 ,u64, u128, usize
+f32, f64
+num
+
+vec, slice, hash, heap, collections // heap: nightly-only experimental API
+
+string, ascii, fmt
+
+default
+
+marker, clone, convert, cmp, iter
+
+ops, ffi
+
+option, result, panic, error
+
+io
+fs, path
+mem, thread, sync
+process, env
+net
+time
+os
+
+ptr, boxed, borrow, cell, any, rc
+
+prelude
+
+intrinsics // intrinsics: nightly-only experimental API
+raw // raw: nightly-only experimental API
+

πŸ”Ž When examining Rust’s source code, you can see that the src directory is a workspace. Even though it is having many library crates, by examining root Cargo.toml file you can easily identify that main crates are rustc(compiler) and libstd (std). In libstd/lib.rs std modules have been re-exported via pub use and the original location of most of the std modules is src/libcore.

Few important std modules are,

  • std::io - Core I/O functionality
  • std::fs - Filesystem specific functionality
  • std::path - Cross-platform path specific functionality
  • std::env - Process’s environment related functionality
  • std::mem - Memory related functionality
  • std::net - TCP/UDP communication
  • std::os - OS specific functionality
  • std::thread - Native threads specific functionality
  • std::collections - Core Collection types

πŸ’― Refer Rust Standard Library Documentation for more details.

Preludes

Even though Rust std contains many modules, by default it doesn’t load each and everything of std library on every rust program. Instead, it loads only the smallest list of things which require for almost every single Rust program. These are called preludes. They import only,

// Reexported core operators
+pub use marker::{Copy, Send, Sized, Sync};
+pub use ops::{Drop, Fn, FnMut, FnOnce};
+
+// Reexported functions
+pub use mem::drop;
+
+// Reexported types and traits
+pub use boxed::Box;
+pub use borrow::ToOwned;
+pub use clone::Clone;
+pub use cmp::{PartialEq, PartialOrd, Eq, Ord};
+pub use convert::{AsRef, AsMut, Into, From};
+pub use default::Default;
+pub use iter::{Iterator, Extend, IntoIterator};
+pub use iter::{DoubleEndedIterator, ExactSizeIterator};
+pub use option::Option::{self, Some, None};
+pub use result::Result::{self, Ok, Err};
+pub use slice::SliceConcatExt;
+pub use string::{String, ToString};
+pub use vec::Vec;
+

Preludes have been imported explicitly on libstd/lib.rs and the whole list can be seen on libstd/prelude/v1.rs.

⭐️ So technically, Rust inserts,

  • extern crate std; : into the crate root of every crate
  • use std::prelude::v1::*; : into every module +So you don’t need to import these each time.

The concept of preludes is quite common on Rust libraries. Even some modules inside std crate (ex.std::io) and many libraries (ex. Diesel) are having their own prelude modules.

⭐️ But preludes are used to create a single place to import all important components which are required while using the library. They do not load automatically unless you imported them manually. Only std::prelude imports automatically in every Rust programs.

\ No newline at end of file diff --git a/docs/docs/structs/index.html b/docs/docs/structs/index.html new file mode 100644 index 0000000..6fab996 --- /dev/null +++ b/docs/docs/structs/index.html @@ -0,0 +1,66 @@ +Structs Β· Learning Rust +

Structs

⭐️ Structs are used to encapsulate related properties into one unified data type.

πŸ’‘ By convention, the name of the struct should follow PascalCase.

There are 3 variants of structs,

  1. C-like structs
  • One or more comma-separated name:value pairs
  • Brace-enclosed list
  • Similar to classes (without its methods) in OOP languages
  • Because fields have names, we can access them through dot notation
  1. Tuple structs
  • One or more comma-separated values
  • A parenthesized list like tuples
  • Looks like a named tuples
  1. Unit structs
  • A struct with no members at all
  • It defines a new type but it resembles an empty tuple, ()
  • Rarely in use, useful with generics

⭐️ When regarding OOP in Rust, attributes and methods are placed separately on structs and traits. Structs contain only attributes, traits contain only methods. They are getting connected via impls.

πŸ’‘More complex examples can be found on impls & traits, lifetimes and modules sections.

C-like structs

// Struct Declaration
+struct Color {
+    red: u8,
+    green: u8,
+    blue: u8
+}
+
+fn main() {
+  // Creating an instance
+  let black = Color {red: 0, green: 0, blue: 0};
+
+  // Accessing its fields using dot notation
+  println!("Black = rgb({}, {}, {})", black.red, black.green, black.blue); //Black = rgb(0, 0, 0)
+
+  // Structs are immutable by default, use `mut` to make it mutable but doesn't support field level mutability
+  let mut link_color = Color {red: 0,green: 0,blue: 255};
+  link_color.blue = 238;
+  println!("Link Color = rgb({}, {}, {})", link_color.red, link_color.green, link_color.blue); //Link Color = rgb(0, 0, 238)
+
+  // Copy elements from another instance
+  let blue = Color {blue: 255, .. link_color};
+  println!("Blue = rgb({}, {}, {})", blue.red, blue.green, blue.blue); //Blue = rgb(0, 0, 255)
+
+  // Destructure the instance using a `let` binding, this will not destruct blue instance
+  let Color {red: r, green: g, blue: b} = blue;
+  println!("Blue = rgb({}, {}, {})", r, g, b); //Blue = rgb(0, 0, 255)
+
+  // Creating an instance via functions & accessing its fields
+  let midnightblue = get_midnightblue_color();
+  println!("Midnight Blue = rgb({}, {}, {})", midnightblue.red, midnightblue.green, midnightblue.blue); //Midnight Blue = rgb(25, 25, 112)
+
+  // Destructure the instance using a `let` binding
+  let Color {red: r, green: g, blue: b} = get_midnightblue_color();
+  println!("Midnight Blue = rgb({}, {}, {})", r, g, b); //Midnight Blue = rgb(25, 25, 112)
+}
+
+fn get_midnightblue_color() -> Color {
+    Color {red: 25, green: 25, blue: 112}
+}
+

Tuple structs

⭐️ When a tuple struct has only one element, we call it newtype pattern. Because it helps to create a new type.

struct Color(u8, u8, u8);
+struct Kilometers(i32);
+
+fn main() {
+  // Creating an instance
+  let black = Color(0, 0, 0);
+
+  // Destructure the instance using a `let` binding, this will not destruct black instance
+  let Color(r, g, b) = black;
+  println!("Black = rgb({}, {}, {})", r, g, b); //black = rgb(0, 0, 0);
+
+  // Newtype pattern
+  let distance = Kilometers(20);
+  // Destructure the instance using a `let` binding
+  let Kilometers(distance_in_km) = distance;
+  println!("The distance: {} km", distance_in_km); //The distance: 20 km
+}
+

Unit structs

This is rarely useful on its own. But in combination with other features, it can become useful.

πŸ“– ex: A library may ask you to create a structure that implements a certain trait to handle events. If you don’t have any data you need to store in the structure, you can create a unit-like struct.

struct Electron;
+
+fn main() {
+  let x = Electron;
+}
+
\ No newline at end of file diff --git a/docs/docs/unwrap-and-expect/index.html b/docs/docs/unwrap-and-expect/index.html new file mode 100644 index 0000000..dca2ca0 --- /dev/null +++ b/docs/docs/unwrap-and-expect/index.html @@ -0,0 +1,162 @@ +Unwrap and Expect Β· Learning Rust +

Unwrap and Expect

unwrap()

  • If an Option type has Some value or a Result type has a Ok value, the value inside them passes to the next step.
  • If the Option type has None value or the Result type has Err value, program panics; If Err, panics with the error message.

The functionality is bit similar to the following codes, which are using match instead unwrap().

Example with Option and match, before using unwrap()

fn main() {
+    let x;
+    match get_an_optional_value() {
+        Some(v) => x = v, // if Some("abc"), set x to "abc"
+        None => panic!(), // if None, panic without any message
+    }
+
+    println!("{}", x); // "abc" ; if you change line 14 `false` to `true`
+}
+
+fn get_an_optional_value() -> Option<&'static str> {
+
+    //if the optional value is not empty
+    if false {
+        return Some("abc");
+    }
+    
+    //else
+    None
+}
+
+
+// --------------- Compile-time error ---------------
+thread 'main' panicked at 'explicit panic', src/main.rs:5:17
+

Example with Result and match, before using unwrap()

fn main() {
+    let x;
+    match function_with_error() {
+        Ok(v) => x = v, // if Ok(255), set x to 255
+        Err(e) => panic!(e), // if Err("some message"), panic with error message "some message"
+    }
+
+    println!("{}", x); // 255 ; if you change line 13 `true` to `false`
+}
+
+fn function_with_error() -> Result<u64, String> {
+    //if error happens
+    if true {
+        return Err("some message".to_string());
+    }
+
+    // else, return valid output
+    Ok(255)
+}
+
+
+// ---------- Compile-time error ----------
+thread 'main' panicked at 'some message', src/main.rs:5:19
+

Same codes in above main functions can be written with unwrap() using two lines.

// 01. unwrap error message for None
+fn main() {
+    let x = get_an_optional_value().unwrap();
+
+    println!("{}", x);
+}
+
+// --------------- Compile-time error ---------------
+thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', libcore/option.rs:345:21
+
+
+// 02. unwrap error message for Err
+fn main() {
+    let x = function_with_error().unwrap();
+
+    println!("{}", x);
+}
+
+// --------------- Compile-time error ---------------
+thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: "some message"', libcore/result.rs:945:5
+

⭐ But as you can see, when using unwrap() error messages are not showing the exact line numbers where the panic happens.

expect()

Similar to unwrap() but can set a custom message for the panics.

// 01. expect error message for None
+fn main() {
+    let n: Option<i8> = None;
+    
+    n.expect("empty value returned");
+}
+
+// --------------- Compile-time error ---------------
+thread 'main' panicked at 'empty value returned', libcore/option.rs:989:5
+
+
+// 02. expect error message for Err
+fn main() {
+    let e: Result<i8, &str> = Err("some message");
+
+    e.expect("expect error message");
+}
+
+// --------------- Compile-time error ---------------
+thread 'main' panicked at 'expect error message: "some message"', libcore/result.rs:945:5
+

unwrap_err() and expect_err() for Result types

The opposite case of unwrap() and expect(); Panics with Ok values, instead Err. Both print the value inside Ok on the error message.

πŸ’‘ Usually use with tests.

// 01. unwrap_err error message for Ok
+fn main() {
+    let o: Result<i8, &str> = Ok(8);
+
+    o.unwrap_err();
+}
+
+// ---------- Compile-time error ----------
+thread 'main' panicked at 'called `Result::unwrap_err()` on an `Ok` value: 8', libcore/result.rs:945:5
+
+
+// 02. expect_err error message for Ok
+fn main() {
+    let o: Result<i8, &str> = Ok(8);
+
+    o.expect_err("Should not get Ok value");
+}
+
+// ---------- Compile-time error ----------
+thread 'main' panicked at 'Should not get Ok value: 8', libcore/result.rs:945:5
+

unwrap_or(), unwrap_or_default() and unwrap_or_else()

πŸ’‘ These are bit similar to unwrap(), If an Option type has Some value or a Result type has a Ok value, the value inside them passes to the next step. But when having None or Err, the functionalities are bit different.

  • unwrap_or()Β : With None or Err, the value you passes to unwrap_or() is passing to the next step. But the data type of the value you passes should match with the data type of the relevant Some or Ok.
fn main() {
+    let v1 = 8;
+    let v2 = 16;
+
+    let s_v1 = Some(8);
+    let n = None;
+
+    assert_eq!(s_v1.unwrap_or(v2), v1); // Some(v1) unwrap_or v2 = v1
+    assert_eq!(n.unwrap_or(v2), v2);    // None unwrap_or v2 = v2
+
+    let o_v1: Result<i8, &str> = Ok(8);
+    let e: Result<i8, &str> = Err("error");
+
+    assert_eq!(o_v1.unwrap_or(v2), v1); // Ok(v1) unwrap_or v2 = v1
+    assert_eq!(e.unwrap_or(v2), v2);    // Err unwrap_or v2 = v2
+}
+
  • unwrap_or_default()Β : With None or Err, the default value of the data type of the relevant Some or Ok, is passing to the next step.
fn main() {
+    let v = 8;
+    let v_default = 0;
+
+    let s_v: Option<i8> = Some(8);
+    let n: Option<i8> = None;
+
+    assert_eq!(s_v.unwrap_or_default(), v);       // Some(v) unwrap_or_default = v
+    assert_eq!(n.unwrap_or_default(), v_default); // None unwrap_or_default = default value of v
+
+    let o_v: Result<i8, &str> = Ok(8);
+    let e: Result<i8, &str> = Err("error");
+
+    assert_eq!(o_v.unwrap_or_default(), v);       // Ok(v) unwrap_or_default = v
+    assert_eq!(e.unwrap_or_default(), v_default); // Err unwrap_or_default = default value of v
+}
+
  • unwrap_or_else()Β : Similar to unwrap_or(). The only difference is, instead of passing a value, you have to pass a closure which returns a value with the same data type of the relevant Some or Ok.
fn main() {
+    let v1 = 8;
+    let v2 = 16;
+
+    let s_v1 = Some(8);
+    let n = None;
+    let fn_v2_for_option = || 16;
+
+    assert_eq!(s_v1.unwrap_or_else(fn_v2_for_option), v1); // Some(v1) unwrap_or_else fn_v2 = v1
+    assert_eq!(n.unwrap_or_else(fn_v2_for_option), v2);    // None unwrap_or_else fn_v2 = v2
+
+    let o_v1: Result<i8, &str> = Ok(8);
+    let e: Result<i8, &str> = Err("error");
+    let fn_v2_for_result = |_| 16;
+
+    assert_eq!(o_v1.unwrap_or_else(fn_v2_for_result), v1); // Ok(v1) unwrap_or_else fn_v2 = v1
+    assert_eq!(e.unwrap_or_else(fn_v2_for_result), v2);    // Err unwrap_or_else fn_v2 = v2
+}
+
\ No newline at end of file diff --git a/docs/docs/use/index.html b/docs/docs/use/index.html new file mode 100644 index 0000000..37f4352 --- /dev/null +++ b/docs/docs/use/index.html @@ -0,0 +1,95 @@ +Use Β· Learning Rust +

Use

Let’s see the main usages of the use keyword.

01. Bind a full path to a new name

Mainly use keyword is used to bind a full path of an element to a new name. So the user doesn’t want to repeat the full path each time.

// -- Initial code without the `use` keyword --
+mod phrases { 
+  pub mod greetings { 
+    pub fn hello() { 
+      println!("Hello, world!");
+    }
+  }
+}
+
+fn main() { 
+  phrases::greetings::hello(); // Using full path
+}
+
+
+// -- Usage of the `use` keyword --
+// 01. Create an alias for module
+use phrases::greetings;
+fn main() { 
+  greetings::hello();
+}
+
+// 02. Create an alias for module elements
+use phrases::greetings::hello;
+fn main() { 
+  hello();
+}
+
+// 03. Customize names with the `as` keyword
+use phrases::greetings::hello as greet;
+fn main() { 
+  greet();
+}
+

02. Import elements to scope

Another common usage of use is importing elements to scope. Remember that, this is also a bit similar to creating an alias and using it instead of using the full path.

fn hello() -> String {
+  "Hello, world!".to_string()
+}
+
+#[cfg(test)]
+mod tests {
+  use super::hello; // Import the `hello()` function into the scope
+    
+  #[test]
+  fn test_hello() {
+    assert_eq!("Hello, world!", hello()); // If not using the above `use` statement, we can run same via `super::hello()`
+  }
+}
+

πŸ’‘ By default, use declarations use absolute paths, starting from the crate root. But self and super declarations make that path relative to the current module.

Same way the use keyword is used to import the elements of other crates including the std, Rust’s Standard Library.

// -- 01. Importing elements --
+use std::fs::File;
+
+fn main() {
+    File::create("empty.txt").expect("Can not create the file!");
+}
+
+
+// -- 02. Importing module and elements --
+use std::fs::{self, File} // `use std::fs; use std::fs::File;`
+
+fn main() {
+    fs::create_dir("some_dir").expect("Can not create the directry!");
+    File::create("some_dir/empty.txt").expect("Can not create the file!");
+}
+
+
+// -- 03. Importing multiple elements --
+use std::fs::File;
+use std::io::{BufReader, BufRead}; // `use std::io::BufReader; use std::io::BufRead;`
+
+fn main() {
+    let file = File::open("src/hello.txt").expect("file not found");
+    let buf_reader = BufReader::new(file);
+
+    for line in buf_reader.lines() {
+        println!("{}", line.unwrap());
+    }
+}
+

We don’t need to use extern crate std; when using the std library. We will discuss more about this under the Standard Library section.

πŸ’‘ use statements import only what we’ve specified into the scope, instead of importing all elements of a module or crate. So it improves the efficiency of the program.

03. Re-exporting

Another special case is pub use. When creating a module, you can export things from another module into your module. So after that, they can be accessed directly from your module. This is called re-exporting.

// ↳ main.rs
+mod phrases;
+
+fn main() {
+    phrases::hello(); // Not directly map
+}
+
+// ↳ phrases/mod.rs
+pub mod greetings;
+
+pub use self::greetings::hello; // Re-export `greetings::hello` to phrases
+
+// ↳ phrases/greetings.rs
+pub fn hello() {
+  println!("Hello, world!");
+}
+

This pattern is quite common in large libraries. It helps to hide the complexity of the internal module structure of the library from users. Because users don’t need to know/follow the whole directory map of the elements of the library while working with them.

\ No newline at end of file diff --git a/docs/docs/variable-bindings-constants-and-statics/index.html b/docs/docs/variable-bindings-constants-and-statics/index.html new file mode 100644 index 0000000..d2431a6 --- /dev/null +++ b/docs/docs/variable-bindings-constants-and-statics/index.html @@ -0,0 +1,43 @@ +Variable bindings, Constants & Statics Β· Learning Rust +

Variable bindings, Constants & Statics

Variable bindings, Constants & Statics

⭐️ In Rust, variables are immutable by default, so we call them Variable bindings. To make them mutable, the mut keyword is used.

⭐️ Rust is a statically typed language; it checks data types at compile-time. But it doesn’t require you to actually type it when declaring variable bindings. In that case, the compiler checks the usage and sets a better data type for it. But for constants and statics, you must annotate the type. Types come after a colon(:).

πŸ’­ In the following examples, we will use data types like bool, i32, i64 and f64. Don’t worry about them for now; they’ll be discussed later.

  • Variable bindings

The let keyword is used in binding expressions. We can bind a name to a value or a function. Also, because the left-hand side of a let expression is a “pattern”, you can bind multiple names to a set of values or function values.

let a; // Declaration; without data type
+a = 5; // Assignment
+
+let b: i8; // Declaration; with data type 
+b = 5;
+
+let t = true;        // Declaration + assignment; without data type
+let f: bool = false; // Declaration + assignment; with data type
+
+let (x, y) = (1, 2); // x = 1 and y = 2
+
+let mut z = 5;
+z = 6;
+
+let z = { x + y }; // z = 3
+
+let z = {
+    let x = 1;
+    let y = 2;
+
+    x + y
+}; // z = 3
+
  • Constants

The const keyword is used to define constants and after the assignment their values are not allowed to change. They live for the entire lifetime of a program but has no fixed address in the memory.

const N: i32 = 5;
+
  • Statics

The static keyword is used to define a “global variable” type facility. There is only one instance for each value, and it’s at a fixed location in memory.

static N: i32 = 5;
+

πŸ’­ While you need constants, always use const, instead of static. It’s pretty rare that you actually want a memory location associated with your constant, and using a const allows for optimizations like constant propagation, not only in your crate but also in downstream crates.

Variable Shadowing

Sometimes, while dealing with data, initially we get them in one unit but need to transform them into another unit for further processing. In this situation, instead of using different variable names, Rust allows us to redeclare the same variable with a different data type and/ or with a different mutability setting. We call this Shadowing.

fn main() {
+    let x: f64 = -20.48; // float
+    let x: i64 = x.floor() as i64; // int
+    println!("{}", x); // -21
+
+    let s: &str = "hello"; // &str
+    let s: String = s.to_uppercase(); // String
+    println!("{}", s) // HELLO
+}
+

πŸ‘¨β€πŸ« Before going to the next…

  • The naming convention for the variable bindings is using the snake_case. But, for constants and statics, we should follow the SCREAMING_SNAKE_CASE.

  • Usually, constants and statics are placed at the top of the code file, outside the functions (after module imports/ use declarations).

const PI: f64 = 3.14159265359;
+
+fn main() {
+    println!("Ο€ value is {}", PI);
+}
+
\ No newline at end of file diff --git a/docs/docs/vectors/index.html b/docs/docs/vectors/index.html new file mode 100644 index 0000000..6dc1b0f --- /dev/null +++ b/docs/docs/vectors/index.html @@ -0,0 +1,52 @@ +Vectors Β· Learning Rust +

Vectors

If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of a re-sizable array but all elements must be in the same type.

⭐️ It’s a generic type, written as Vec<T>Β . T can have any type, ex. The type of a Vec of i32s is Vec<i32>. Also, Vectors always allocate their data in a dynamically allocated heap.

Create empty vector

let mut a = Vec::new(); //1.With new() keyword
+let mut b = vec![]; //2.Using the vec! macro
+

Create with data types

let mut a2: Vec<i32> = Vec::new();
+let mut b2: Vec<i32> = vec![];
+let mut b3 = vec![1i32, 2, 3];//Suffixing 1st value with data type
+
+let mut b4 = vec![1, 2, 3];
+let mut b5: Vec<i32> = vec![1, 2, 3];
+let mut b6  = vec![1i32, 2, 3];
+let mut b7 = vec![0; 10]; //Ten zeroes
+

Access and change data

//Accessing and changing existing data
+let mut c = vec![5, 4, 3, 2, 1];
+c[0] = 1;
+c[1] = 2;
+//c[6] = 2; Cannot assign values this way, index out of bounds
+println!("{:?}", c); //[1, 2, 3, 2, 1]
+
+//push and pop
+let mut d: Vec<i32> = Vec::new();
+d.push(1); //[1] : Add an element to the end
+d.push(2); //[1, 2]
+d.pop(); //[1] : : Remove an element from the end
+
+
+// πŸ”Ž Capacity and reallocation
+let mut e: Vec<i32> = Vec::with_capacity(10);
+println!("Length: {}, Capacity : {}", e.len(), e.capacity()); //Length: 0, Capacity : 10
+
+// These are all done without reallocating...
+for i in 0..10 {
+    e.push(i);
+}
+// ...but this may make the vector reallocate
+e.push(11);
+

⭐️ Mainly a vector represent 3 things,

  • A pointer to the data
  • No of elements currently have(length)
  • Capacity (Amount of space allocated for any future elements).

If the length of a vector exceeds its capacity, its capacity will be increased automatically. But its elements will be reallocated(which can be slow). So always use Vec::with_capacity whenever it’s possible.

πŸ’‘ The String data type is a UTF-8 encoded vector. But you can not index into a String because of encoding.

πŸ’― Vectors can be used with iterators in three ways,

let mut v = vec![1, 2, 3, 4, 5];
+
+for i in &v {
+    println!("A reference to {}", i);
+}
+
+for i in &mut v {
+    println!("A mutable reference to {}", i);
+}
+
+for i in v {
+    println!("Take ownership of the vector and its element {}", i);
+}
+
\ No newline at end of file diff --git a/docs/docs/why-rust/index.html b/docs/docs/why-rust/index.html new file mode 100644 index 0000000..59a8c3b --- /dev/null +++ b/docs/docs/why-rust/index.html @@ -0,0 +1,5 @@ +Why Rust? Β· Learning Rust +

Why Rust?

History of Rust

Rust was initially designed and developed by former Mozilla employee Graydon Hoare as a personal project. Mozilla began sponsoring the project in 2009 and announced it in 2010. But the first stable release, Rust 1.0, was released on May 15, 2015.

Since Rust 1.0, major updates have been released as Editions approximately every three years: Rust 2015 (with the release of Rust 1.0) , Rust 2018, Rust 2021, and Rust 2024, all maintaining backward compatibility.

Initial Goals

The goal of Rust is to be a good programming language for creating highly concurrent, safe and performant systems.

“Rust is a systems programming language focused on three goals: safety, speed, and concurrency.”
~ Rust Documentation

Rust is a very young and very modern language. It’s a compiled programming language and it uses LLVM on the backend. Also, Rust is a multi-paradigm programming language, which supports imperative procedural, concurrent actor, object-oriented and pure functional styles. It also supports generic programming and metaprogramming, in both static and dynamic styles.

One of Rust’s most unique and compelling features is Ownership, which is used to achieve memory safety. Rust creates memory pointers optimistically, checks memory pointers’ limited accesses at compile-time with the usage of References and Borrowing. And it does automatic compile-time memory management by checking the Lifetimes.

Influences

Its design elements came from a wide range of sources.

  • Abstract Machine Model: C
  • Data types: C, SML, OCaml, Lisp, Limbo
  • Optional Bindings: Swift
  • Hygienic Macros: Scheme
  • Functional Programming: Haskell, OCaml, F#
  • Attributes: ECMA-335
  • Memory Model and Memory Management: C++, ML Kit, Cyclone
  • Type Classes: Haskell
  • Crate: Assembly in the ECMA-335 CLI model
  • Channels and Concurrency: Newsqueak, Alef, Limbo
  • Message passing and Thread failure: Erlang

and etc.

Rust doesn’t use a built-in runtime or an automated garbage collection system (GC).

πŸ’‘ However, async Rust requires an async runtime, which is provided by community-maintained crates like tokio, async-std, soml etc. The async runtime will be bundled into the final executable.

Rust compiler observes the code at compile-time and helps to prevent many types of errors that are possible to write in C, C++ like programming languages.

πŸ‘¨β€πŸ« Before going to the next…

\ No newline at end of file diff --git a/docs/docs/workspaces/index.html b/docs/docs/workspaces/index.html new file mode 100644 index 0000000..718cfeb --- /dev/null +++ b/docs/docs/workspaces/index.html @@ -0,0 +1,55 @@ +Workspaces Β· Learning Rust +

Workspaces

When the code base is getting larger, you might need to work with multiple crates on the same project. Rust supports this via Workspaces. You can analyze (cargo check), build, run tests or generate docs for all crates at once by running cargo commands from the project root.

⭐️ When working on multiple crates same time, there is a higher possibility of having shared dependencies on crates. To prevent downloading and compiling the same dependency multiple times, Rust uses a shared build directory under the project root, while running cargo build from the project root.

Let’s create a library crate with a simple hello world function and a binary crate which uses the library crate.

Assume we run,

mkdir greetings
+touch greetings/Cargo.toml
+cargo new greetings/lib --lib
+cargo new greetings/examples/hello
+

That generates,

greetings
+ β”œβ”€β”€ Cargo.toml
+ β”œβ”€β”€ examples
+ β”‚  └── hello
+ β”‚     β”œβ”€β”€ Cargo.toml
+ β”‚     └── src
+ β”‚        └── main.rs
+ └── lib
+    β”œβ”€β”€ Cargo.toml
+    └── src
+       └── lib.rs
+

We have to modify the following files,

// 01. greetings/Cargo.toml to mark as a workspace and to add members
+[workspace]
+members = [
+    "lib",
+    "examples/hello"
+]
+
+// 02.1 greetings/lib/Cargo.toml to change the package name to greetings
+[package]
+name = "greetings"
+version = "0.1.0"
+authors = ["Dumindu Madunuwan"]
+
+[dependencies]
+
+// 02.2 greetings/lib/src/lib.rs to add a simple hello world function
+pub fn hello() {
+    println!("Hello, world!");
+}
+
+// 03.1 greetings/examples/hello/Cargo.toml to add the `greetings` lib as a dependency
+[package]
+name = "hello"
+version = "0.1.0"
+authors = ["Dumindu Madunuwan"]
+
+[dependencies]
+greetings = { path = "../../lib" }
+
+// 03.2 greetings/examples/hello/src/main.rs to import the `greetings` lib and call its hello world function
+extern crate greetings;
+
+fn main() {
+    greetings::hello();
+}
+

πŸ’‘ On Linux and Mac, you can run cargo commands on each crate without changing the working directory all the times via Subshells (A command list embedded between parentheses). For example, if you are in the greetings directory, even you run (cd examples/hello && cargo run) your working directory will be kept as same in greetings folder.

πŸ”Ž rust-lang/rust source folder is a good example for a workspace.

\ No newline at end of file diff --git a/docs/favicon/android-chrome-192x192.png b/docs/favicon/android-chrome-192x192.png new file mode 100644 index 0000000..918f1d3 Binary files /dev/null and b/docs/favicon/android-chrome-192x192.png differ diff --git a/docs/favicon/android-chrome-512x512.png b/docs/favicon/android-chrome-512x512.png new file mode 100644 index 0000000..e46db07 Binary files /dev/null and b/docs/favicon/android-chrome-512x512.png differ diff --git a/docs/favicon/apple-touch-icon.png b/docs/favicon/apple-touch-icon.png new file mode 100644 index 0000000..84816ca Binary files /dev/null and b/docs/favicon/apple-touch-icon.png differ diff --git a/docs/favicon/favicon-16x16.png b/docs/favicon/favicon-16x16.png new file mode 100644 index 0000000..59a58e0 Binary files /dev/null and b/docs/favicon/favicon-16x16.png differ diff --git a/docs/favicon/favicon-32x32.png b/docs/favicon/favicon-32x32.png new file mode 100644 index 0000000..a680bb8 Binary files /dev/null and b/docs/favicon/favicon-32x32.png differ diff --git a/docs/favicon/favicon.ico b/docs/favicon/favicon.ico new file mode 100644 index 0000000..4f9e2b4 Binary files /dev/null and b/docs/favicon/favicon.ico differ diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..9439cc8 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,3 @@ +Learning Rust Β· Rust Programming Language Tutorials for Everyone! +

Rust Illuminated.Grasp Quickly.

Rust Programming Language Tutorials for Everyone!

Get Started +GitHub
\ No newline at end of file diff --git a/docs/index.xml b/docs/index.xml new file mode 100644 index 0000000..ffaf921 --- /dev/null +++ b/docs/index.xml @@ -0,0 +1,503 @@ +Learning Rusthttps://learning-rust.github.io/Recent content on Learning RustHugoen-USBorrowinghttps://learning-rust.github.io/docs/borrowing/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/borrowing/<p>In real life applications, most of the times we have to pass variable bindings to other functions or assign them to other variable bindings. In this case, we are <strong>referencing</strong> the original binding; <strong>borrow</strong> the data of it.</p> +<h2 id="what-is-borrowing">What is Borrowing?</h2> +<blockquote> +<p><a href="https://github.com/nikomatsakis/rust-tutorials-keynote/blob/master/Ownership%20and%20Borrowing.pdf" target="_blank" >Borrow (verb)</a><br> +To receive something with the promise of returning it.</p></blockquote> +<h2 id="shared--mutable-borrowings">Shared &amp; Mutable borrowings</h2> +<p>⭐️ There are two types of Borrowing,</p> +<ol> +<li> +<p><strong>Shared Borrowing</strong> <code>(&amp;T)</code></p> +<ul> +<li>A piece of data can be <strong>borrowed by a single or multiple users</strong>, but <strong>data should not be altered</strong>.</li> +</ul> +</li> +<li> +<p><strong>Mutable Borrowing</strong> <code>(&amp;mut T)</code></p>Cargo, Crates and Basic Project Structurehttps://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/<h2 id="cargo">Cargo</h2> +<p>Cargo is Rust’s built-in package manager and build system. It also supports the following actions,</p> +<table> + <thead> + <tr> + <th>Command</th> + <th>Action</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>cargo new</code></td> + <td>Create a new project</td> + </tr> + <tr> + <td><code>cargo init</code></td> + <td>Create a new project in an existing directory</td> + </tr> + <tr> + <td><code>cargo check</code></td> + <td>Verify the project compiles without errors</td> + </tr> + <tr> + <td><code>cargo build</code></td> + <td>Build the executable</td> + </tr> + <tr> + <td><code>cargo run</code></td> + <td>Build the executable and run</td> + </tr> + </tbody> +</table> +<blockquote> +<p>πŸ’‘ The <code>cargo check</code> command verifies that the project compiles without errors, without producing an executable. +Thus, it is often faster than <code>cargo build</code>.</p>Code Organizationhttps://learning-rust.github.io/docs/code-organization/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/code-organization/<p>When a single code block is getting larger, it should be decomposed into smaller pieces and should be organized in a proper manner. Rust supports different levels of code organization.</p> +<h2 id="1-functions">1. Functions</h2> +<h2 id="2-modules">2. Modules</h2> +<p>Can be mapped to a,</p> +<ul> +<li><strong>Inline module</strong></li> +<li><strong>File</strong></li> +<li><strong>Directory hierarchy</strong></li> +</ul> +<h2 id="3-crates">3. Crates</h2> +<p>Can be mapped to a,</p> +<ul> +<li> +<p><strong>lib.rs file on the same executable crate</strong></p> +</li> +<li> +<p><strong>Dependency crate specified on Cargo.toml</strong></p> +<p>Can be specified from,</p> +<ul> +<li><strong>Path</strong></li> +<li><strong>Git repository</strong></li> +<li><strong>crates.io</strong></li> +</ul> +</li> +</ul> +<h2 id="4-workspaces">4. Workspaces</h2> +<p>Helps to manage multiple crates as a single project.</p>Combinatorshttps://learning-rust.github.io/docs/combinators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/combinators/<h2 id="what-is-a-combinator">What is a combinator?</h2> +<ul> +<li> +<p>One meaning of β€œcombinator” is a more informal sense referring to the <strong>combinator pattern</strong>, a style of organizing libraries centered around the idea of combining things. Usually there is <strong>some type T</strong>, some <strong>functions for constructing β€œprimitive” values of type T</strong>, and some β€œ<strong>combinators</strong>” which can <strong>combine values of type T</strong> in various ways to <strong>build up more complex values of type T</strong>. The other definition is <strong>&ldquo;function with no free variables&rdquo;</strong>. +__ <a href="https://wiki.haskell.org/Combinator" target="_blank" >wiki.haskell.org</a></p>Comments and Documenting the codehttps://learning-rust.github.io/docs/comments-and-documenting-the-code/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/comments-and-documenting-the-code/<h2 id="comments">Comments</h2> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// Line comments +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="cm">/* Block comments */</span><span class="w"> +</span></span></span></code></pre></div><p>Nested block comments are supported.</p> +<p>πŸ’‘ <strong>By convention, try to avoid using block comments. Use line comments instead.</strong></p> +<h2 id="doc-comments">Doc Comments</h2> +<p><a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#cargo" >As we discussed</a>, we can generate the project documentation via <a href="https://doc.rust-lang.org/stable/rustdoc/" target="_blank" >rustdoc</a> by running the <strong><code>cargo doc</code></strong> command. It uses the doc comments to generate the documentation.</p> +<p>πŸ’‘ Usually we are adding doc comments on library crates. Also, we can use <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank" >Markdown notations</a> inside the doc comments.</p>Control Flowshttps://learning-rust.github.io/docs/control-flows/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/control-flows/<h2 id="if---else-if---else">if - else if - else</h2> +<ul> +<li>Using only <code>if</code> block.</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, child!&#34;</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><ul> +<li>Using only <code>if</code> and <code>else</code> blocks.</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Even&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Odd&#34;</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><ul> +<li>Using with <code>let</code> statement.</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span>: <span class="kt">u8</span> <span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">is_below_eighteen</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">false</span><span class="w"> </span><span class="p">};</span><span class="w"> </span><span class="c1">// true +</span></span></span></code></pre></div><ul> +<li>More examples,</li> +</ul> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// i. A simple example +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Small&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Medium&#34;</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Large&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// ii. Let&#39;s refactor above code +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&#34;Small&#34;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&#34;Medium&#34;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&#34;Large&#34;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Current team size : </span><span class="si">{}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium +</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// iii. Let&#39;s refactor further +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Small&#34;</span><span class="w"> </span><span class="c1">// ⭐️ no ; +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Medium&#34;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Large&#34;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">};</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Current team size : </span><span class="si">{}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">team_size</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium +</span></span></span></code></pre></div><p>⭐️ <strong>Return data type should be the same on each block when using this as an expression.</strong></p>Crateshttps://learning-rust.github.io/docs/crates/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/crates/<p>πŸ’­ Crates are a bit similar to the packages in some other languages. Crates compile individually. If the crate has child file modules, those files will get merged with the crate file and compile as a single unit.</p> +<p>πŸ’­ A crate can produce an executable/ a binary or a library. <code>src/main.rs</code> is the crate root/ entry point for a binary crate and <code>src/lib.rs</code> is the entry point for a library crate.</p>Custom Error Typeshttps://learning-rust.github.io/docs/custom-error-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/custom-error-types/<p>Rust allow us to create our own <code>Err</code> types. We call them β€œ<em>Custom Error Types</em>”.</p> +<h2 id="error-trait">Error trait</h2> +<p>As you know <strong>traits define the functionality a type must provide</strong>. But we don’t always need to define new traits for common functionalities, because Rust <strong>standard library provides reusable traits</strong> which can be implemented on our own types. While creating custom error types the <a href="https://doc.rust-lang.org/std/error/trait.Error.html" target="_blank" ><code>std::error::Error</code> trait</a> helps us to convert any type to an <code>Err</code> type.</p>Enumshttps://learning-rust.github.io/docs/enums/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/enums/<p>⭐️ An <strong>enum</strong> is a single type. It contains <strong>variants</strong>, which are possible values of the enum at a given time. For example,</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">enum</span> <span class="nc">Day</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Sunday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Monday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Tuesday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Wednesday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Thursday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Friday</span><span class="p">,</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Saturday</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// The `Day` is the enum +</span></span></span><span class="line"><span class="cl"><span class="c1">// Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are the variants +</span></span></span></code></pre></div><p>⭐️ Variants can be accessed throughΒ :: notation, ex. Day::Sunday</p> +<p>⭐️ Each enum <strong>variant</strong> can have,</p>Error and None Propagationhttps://learning-rust.github.io/docs/error-and-none-propagation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/error-and-none-propagation/<p>We should use panics like <code>panic!()</code>, <code>unwrap()</code>, <code>expect()</code> only if we can not handle the situation in a better way. Also if a function contains expressions which can produce either <code>None</code> or <code>Err</code>,</p> +<ul> +<li>we can handle them inside the same function. Or,</li> +<li>we can return <code>None</code> and <code>Err</code> types immediately to the caller. So the caller can decide how to handle them.</li> +</ul> +<p>πŸ’‘ <code>None</code> types no need to handle by the caller of the function always. But Rusts’ convention to handle <strong><code>Err</code></strong> types is, <strong>return them immediately to the caller to give more control to the caller to decide how to handle them.</strong></p>Functionshttps://learning-rust.github.io/docs/functions/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions/<h2 id="named-functions">Named functions</h2> +<ul> +<li>Named functions are declared with the keyword <strong><code>fn</code></strong></li> +<li>When using <strong>arguments</strong>, you <strong>must declare the data types</strong>.</li> +<li>By default, functions <strong>return an empty <a href="https://learning-rust.github.io/docs/primitive-data-types/#tuple" >tuple</a>/ <code>()</code></strong>. If you want to return a value, the <strong>return type must be specified</strong> after <strong><code>-&gt;</code></strong></li> +</ul> +<h3 id="i-hello-world">i. Hello world</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h3 id="ii-passing-arguments">ii. Passing arguments</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">print_sum</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i8</span><span class="p">,</span><span class="w"> </span><span class="n">b</span>: <span class="kt">i8</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;sum is: </span><span class="si">{}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h3 id="iii-returning-values">iii. Returning values</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 01. Without the return keyword. Only the last expression returns. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// There is no ending ; in the above line. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// It means this is an expression which equals to `return a + 1;`. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 02. With the return keyword. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_two</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// Should use return keyword only on conditional/ early returns. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// Using return keyword in the last expression is a bad practice. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h3 id="iv-function-pointers-usage-as-a-data-type">iv. Function pointers, Usage as a Data Type</h3> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 01. Without type declarations. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 02. With type declarations. +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span>: <span class="nc">fn</span><span class="p">(</span><span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">i32</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h2 id="closures">Closures</h2> +<ul> +<li>Also known as <strong>anonymous functions</strong> or <strong>lambda functions</strong>.</li> +<li>The <strong>data types of arguments and returns are optional <a href="#iv-without-optional-type-declarations-creating-and-calling-together" > ⃰ⁱᡛ</a></strong>.</li> +</ul> +<p>Example with a named function, before using closures.</p>Functions (02)https://learning-rust.github.io/docs/functions-02/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions-02/<p>Functions are the first line of organization in any program.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do one thing +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="n">ask_location</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do another thing +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">ask_location</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Where are you from?&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>We can add unit tests in the same file.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span>-&gt; <span class="nb">String</span> <span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">&#34;Hello, world!&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">()</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="cp">#[test]</span><span class="w"> </span><span class="c1">// Test attribute indicates this is a test function +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">test_greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">assert_eq!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">greet</span><span class="p">())</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// πŸ’‘ Always put test functions inside a tests module with #[cfg(test)] attribute. +</span></span></span><span class="line"><span class="cl"><span class="c1">// cfg(test) module compiles only when running tests. We discuss more about this in the next section. +</span></span></span></code></pre></div><blockquote> +<p>πŸ’­ An <a href="https://doc.rust-lang.org/reference/attributes.html" target="_blank" >attribute</a> is a general, free-form <strong>metadatum</strong> that is interpreted according to name, convention, and language and compiler version.</p>Genericshttps://learning-rust.github.io/docs/generics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/generics/<blockquote> +<p><a href="https://doc.rust-lang.org/beta/book/first-edition/generics.html" target="_blank" >πŸ“–</a> Sometimes, when writing a function or data type, we may want it to work for multiple types of arguments. In Rust, we can do this with generics.</p></blockquote> +<p>πŸ’­ The concept is, instead of declaring a specific data type we use an uppercase letter(or <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a> identifier). ex, <strong>instead of xΒ : u8</strong> we use <strong>xΒ : T</strong>Β . but we have to inform to the compiler that T is a generic type(can be any type) by adding <code>&lt;T&gt;</code> at first.</p>Hello Worldhttps://learning-rust.github.io/docs/hello-world/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/hello-world/<h2 id="hello-world">Hello, World!</h2> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p><code>fn</code> means function. The <code>main</code> function is the beginning of every Rust program.<br> +<code>println!()</code> prints text to the console and its <code>!</code> indicates that it’s a <a href="https://doc.rust-lang.org/book/ch19-06-macros.html" target="_blank" >macro</a> rather than a function.</p> +<blockquote> +<p>πŸ’‘ Rust files should have <code>.rs</code> file extension and if you’re using more than one word for the file name, follow the <a href="https://en.wikipedia.org/wiki/Snake_case" target="_blank" >snake_case</a> convention.</p></blockquote> +<ul> +<li>Save the above code in <code>file.rs</code> , but it can be any name with <code>.rs</code> extension.</li> +<li>Compile it with <code>rustc file.rs</code></li> +<li>Execute it with <code>./file</code> on Linux and Mac or <code>file.exe</code> on Windows</li> +</ul> +<h2 id="rust-playground">Rust Playground</h2> +<p><a href="https://play.rust-lang.org/" target="_blank" >Rust Playground</a> is a web interface for running Rust code.</p>Impls & Traitshttps://learning-rust.github.io/docs/impls-and-traits/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/impls-and-traits/<p>πŸ’‘ When we discussed about <strong>C-like structs</strong>, I mentioned that those are <strong>similar to classes</strong> in OOP languages <strong>but without their methods</strong>. <strong>impls</strong> are <strong>used to define methods</strong> for Rust structs and enums.</p> +<p>πŸ’‘ <strong>Traits</strong> are kind of <strong>similar to interfaces</strong> in OOP languages. They are used to define the functionality a type must provide. Multiple traits can be implemented for a single type.</p> +<p>⭐️️ But traits <strong>can also include default implementations of methods</strong>. Default methods can be overridden when implementing types.</p>Installationhttps://learning-rust.github.io/docs/installation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/installation/<h2 id="rustup">Rustup</h2> +<p>There are many ways to install Rust on your system. For the moment the official way to install Rust is using <a href="https://rustup.rs/" target="_blank" >Rustup</a>.</p> +<p><a href="https://rust-lang.github.io/rustup/index.html" target="_blank" >πŸ“–</a> Rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between <strong>stable, beta, and nightly</strong> compilers and keep them updated. It also makes cross-compiling simpler with binary builds of the standard library for common platforms.</p> +<p><a href="https://rust-lang.github.io/rustup/installation/index.html" target="_blank" >πŸ“–</a> Rustup installs <strong><code>rustc</code>, <code>cargo</code>, <code>rustup</code></strong> and other standard tools to Cargo&rsquo;s <code>bin</code> directory. On Unix it is located at <code>$HOME/.cargo/bin</code> and on Windows at <code>%USERPROFILE%\.cargo\bin</code>. This is the same directory that <code>cargo install</code> will install Rust programs and Cargo plugins.</p>Lifetimeshttps://learning-rust.github.io/docs/lifetimes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/lifetimes/<p>When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.</p> +<p>Think,</p> +<ul> +<li>We have a <strong>variable binding</strong>, <code>a</code>.</li> +<li>We are <strong>referencing</strong> the value of <code>a</code>, <strong>from another variable binding</strong> <code>x</code>. +We have to make sure that <strong><code>a</code> lives until we stop using <code>x</code></strong>.</li> +</ul> +<blockquote> +<p>πŸ”Ž <strong>Memory management</strong> is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used <strong>Manual Memory Management</strong> which <strong>requires the programmer to give manual instructions</strong> to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented <strong>Garbage collection</strong>(GC), a form of <strong>Automatic Memory Management</strong>(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However <strong>Objective-C and Swift</strong> provide similar functionality through <strong>Automatic Reference Counting</strong>(ARC).</p>Moduleshttps://learning-rust.github.io/docs/modules/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/modules/<h2 id="01-in-the-same-file">01. In the same file</h2> +<p>Related code and data are grouped into a module and stored in the same file.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// ⭐️ By default, everything inside a module is private +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// ⭐️ So function has to be public to access from outside +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>Modules can also be nested.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>Private functions can be called from the same module or from a child module.</p>Operatorshttps://learning-rust.github.io/docs/operators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/operators/<ul> +<li> +<h2 id="arithmetic-operators">Arithmetic Operators</h2> +</li> +</ul> +<p><code>+ - * / %</code></p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">5</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//6 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//4 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//10 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">// ⭐️ 2 not 2.5 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//1 +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">5.0</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mf">2.0</span><span class="p">;</span><span class="w"> </span><span class="c1">//2.5 +</span></span></span></code></pre></div><ul> +<li> +<h2 id="comparison-operators">Comparison Operators</h2> +</li> +</ul> +<p><code>== != &lt; &gt; &lt;= &gt;=</code></p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&lt;=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">h</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">&gt;=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// πŸ”Ž +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">&#39;a&#39;</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="sc">&#39;A&#39;</span><span class="p">;</span><span class="w"> </span><span class="c1">//true +</span></span></span></code></pre></div><ul> +<li> +<h2 id="logical-operators">Logical Operators</h2> +</li> +</ul> +<p><code>! &amp;&amp; ||</code></p>Option and Resulthttps://learning-rust.github.io/docs/option-and-result/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/option-and-result/<h2 id="why-option-and-result">Why Option and Result?</h2> +<p>Many languages use <strong><code>null</code>\ <code>nil</code>\ <code>undefined</code> types</strong> to represent empty outputs, and <strong><code>Exceptions</code></strong> to handle errors. Rust skips using both, especially to prevent issues like <strong>null pointer exceptions, sensitive data leakages through exceptions</strong>, etc. Instead, Rust provides two special <strong>generic enums</strong>;<code>Option</code> and <code>Result</code> to deal with above cases.</p> +<blockquote> +<p>πŸ’­ In the previous sections, we have discussed about the basics of <a href="https://learning-rust.github.io/docs/enums" >enums</a>, <a href="https://learning-rust.github.io/docs/generics" >generics</a> and <a href="https://learning-rust.github.io/docs/generics/#generalizing-enums" ><code>Result</code> &amp; <code>Option</code> types</a>.</p>Overviewhttps://learning-rust.github.io/docs/overview/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/overview/<h2 id="about-me">About me</h2> +<blockquote> +<p>πŸ§‘β€πŸ’» I am an expat working in Singapore as a Go Backend and DevOps Engineer. Feel free to reach out if you find any mistakes or anything that needs to be changed, including spelling or grammar errors. Alternatively, you can create a pull request, open an issue, or <a href="https://gist.github.com/dumindu/00a0be2d175ed5ff3bc3c17bbf1ca5b6" target="_blank" >share your awesome ideas in this gist</a>. Good luck with learning Rust!</p></blockquote> +<p><a href="https://github.com/learning-rust/learning-rust.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-rust/learning-rust.github.io?style=for-the-badge&amp;logo=rust&amp;label=learning-rust.github.io&amp;logoColor=333333&amp;labelColor=f9f9f9&amp;color=F46623" alt="learning-rust.github.io"></a> +<a href="https://learning-cloud-native-go.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-cloud-native-go/learning-cloud-native-go.github.io?style=for-the-badge&amp;logo=go&amp;logoColor=333333&amp;label=learning-cloud-native-go.github.io&amp;labelColor=f9f9f9&amp;color=00ADD8" alt="learning-cloud-native-go.github.io"></a></p> +<p><a href="https://github.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/dumindu-866ee7?style=for-the-badge&amp;logo=GitHub&amp;logoColor=333333&amp;labelColor=f9f9f9" alt="github.com"></a> +<a href="https://www.buymeacoffee.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/Buy%20me%20a%20coffee-dumindu-FFDD00?style=for-the-badge&amp;logo=buymeacoffee&amp;logoColor=333333&amp;labelColor=f9f9f9" alt="buymeacoffee"></a></p> +<h2 id="overview">Overview</h2> +<p>This publication has its origins in the posts I authored on Medium at <a href="https://medium.com/learning-rust" target="_blank" >https://medium.com/learning-rust</a>. However, please note that I have ceased updating the Medium posts. All current and future updates, new content, code, and grammar fixes will be exclusively maintained and released here, <a href="https://learning-rust.github.io" target="_blank" >https://learning-rust.github.io</a>.</p>Ownershiphttps://learning-rust.github.io/docs/ownership/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/ownership/<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// [1, 2, 3] [1, 2, 3] +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// Error; use of moved value: `a` +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><p>In the above examples, we are just trying to <strong>assign the value of <code>a</code> to <code>b</code></strong> . Almost the same code in both code blocks, but having <strong>two different data types</strong>. And the second one gives an error. This is because of the <strong>Ownership</strong>.</p>Panickinghttps://learning-rust.github.io/docs/panicking/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/panicking/<h2 id="panic">panic!()</h2> +<ul> +<li>In some cases, when an error occurs we can not do anything to handle it, <strong>if the error is something which should not have happened</strong>. In other words, if it’s an <strong>unrecoverable error</strong>.</li> +<li>Also <strong>when we are not using a feature-rich debugger or proper logs</strong>, sometimes we need to <strong>debug the code by quitting the program from a specific line of code</strong> by printing out a specific message or a value of a variable binding to understand the current flow of the program. +For above cases, we can use <code>panic!</code> macro.</li> +</ul> +<p>⭐ <code>panic!()</code> runs <strong>thread based</strong>. One thread can be panicked, while other threads are running.</p>Primitive Data Typeshttps://learning-rust.github.io/docs/primitive-data-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/primitive-data-types/<ul> +<li> +<h2 id="bool">bool</h2> +</li> +</ul> +<p>true or false</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">bool</span> <span class="o">=</span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ⭐️ no TRUE, FALSE, 1, 0 +</span></span></span></code></pre></div><ul> +<li> +<h2 id="char">char</h2> +</li> +</ul> +<p>A single Unicode scalar value</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">&#39;x&#39;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">char</span> <span class="o">=</span><span class="w"> </span><span class="sc">&#39;😎&#39;</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ⭐️ no &#34;x&#34;, only single quotes +</span></span></span></code></pre></div><p>Because of Unicode support, char is not a single byte, but four(32 bits).</p> +<ul> +<li> +<h2 id="i8-i16-i32-i64-i128">i8, i16, i32, i64, i128</h2> +</li> +</ul> +<p>8, 16, 32, 64 and 128 bit fixed sized signed(+/-) integer types</p>Smart Compilerhttps://learning-rust.github.io/docs/smart-compiler/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/smart-compiler/<h2 id="why-compiler">Why Compiler?</h2> +<p>The Rust compiler does the most significant job to prevent errors in Rust programs. It <strong>analyzes the code at compile-time</strong> and issues warnings, if the code does not follow memory management rules or lifetime annotations correctly.</p> +<p>For example,</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[allow(unused_variables)]</span><span class="w"> </span><span class="c1">//πŸ’‘ A lint attribute used to suppress the warning; unused variable: `b` +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ------ Compile-time error ------ +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">error</span><span class="p">[</span><span class="n">E0382</span><span class="p">]</span>: <span class="nc">use</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">value</span>: <span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">-</span>-&gt; <span class="nc">src</span><span class="o">/</span><span class="n">main</span><span class="p">.</span><span class="n">rs</span>:<span class="mi">6</span>:<span class="mi">22</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">3</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">here</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">4</span><span class="w"> </span><span class="o">|</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">5</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;</span><span class="si">{:?}</span><span class="s">&#34;</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">^</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">used</span><span class="w"> </span><span class="n">here</span><span class="w"> </span><span class="n">after</span><span class="w"> </span><span class="k">move</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">note</span>: <span class="nc">move</span><span class="w"> </span><span class="n">occurs</span><span class="w"> </span><span class="n">because</span><span class="w"> </span><span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w"> </span><span class="n">has</span><span class="w"> </span><span class="k">type</span> <span class="err">`</span><span class="n">std</span>::<span class="n">vec</span>::<span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">i32</span><span class="o">&gt;</span><span class="err">`</span><span class="p">,</span><span class="w"> </span><span class="n">which</span><span class="w"> </span><span class="n">does</span><span class="w"> </span><span class="n">not</span><span class="w"> </span><span class="n">implement</span><span class="w"> </span><span class="n">the</span><span class="w"> </span><span class="err">`</span><span class="nb">Copy</span><span class="err">`</span><span class="w"> </span><span class="k">trait</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">error</span>: <span class="nc">aborting</span><span class="w"> </span><span class="n">due</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">previous</span><span class="w"> </span><span class="n">error</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">For</span><span class="w"> </span><span class="n">more</span><span class="w"> </span><span class="n">information</span><span class="w"> </span><span class="n">about</span><span class="w"> </span><span class="n">this</span><span class="w"> </span><span class="n">error</span><span class="p">,</span><span class="w"> </span><span class="kr">try</span><span class="w"> </span><span class="err">`</span><span class="n">rustc</span><span class="w"> </span><span class="o">--</span><span class="n">explain</span><span class="w"> </span><span class="n">E0382</span><span class="err">`</span><span class="p">.</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ⭐ instead using #[allow(unused_variables)], consider using &#34;let _b = a;&#34; in line 4. +</span></span></span><span class="line"><span class="cl"><span class="c1">// Also you can use &#34;let _ =&#34; to completely ignore return values +</span></span></span></code></pre></div><blockquote> +<p>πŸ’­ In the previous sections, we have discussed memory management concepts like <a href="https://learning-rust.github.io/docs/ownership" >ownership</a>, <a href="https://learning-rust.github.io/docs/borrowing" >borrowing</a>, <a href="https://learning-rust.github.io/docs/lifetimes" >lifetimes</a> and etc.</p>STD, Primitives and Preludeshttps://learning-rust.github.io/docs/std-primitives-and-preludes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/std-primitives-and-preludes/<p>⭐️ In Rust, language elements are implemented by not only <strong><code>std</code> library</strong> crate but also <strong>compiler</strong> as well. Examples,</p> +<ul> +<li><strong><a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >Primitives</a></strong>: Defined by the compiler and methods are implemented by <code>std</code> library directly on primitives.</li> +<li><strong><a href="https://doc.rust-lang.org/std/#macros" target="_blank" >Standard Macros</a></strong>: Defined by both compiler and <code>std</code></li> +</ul> +<p>The <strong><code>std</code></strong> library has been divided into <strong><a href="https://doc.rust-lang.org/std/#modules" target="_blank" >modules</a></strong>, according to the main areas each covered.</p> +<p>⭐️ While primitives are implemented by the <strong>compiler</strong>, the standard library implements the <strong>most useful methods</strong> directly on the primitive types. But some <strong>rarely useful language elements</strong> of some primitives are stored on relevant <strong><code>std</code> modules</strong>. This is why you can see <code>char</code>, <code>str</code> and integer types on both <a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >primitives</a> and <a href="https://doc.rust-lang.org/std/#modules" target="_blank" ><code>std</code> modules</a>.</p>Structshttps://learning-rust.github.io/docs/structs/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/structs/<p>⭐️ Structs are used to <strong>encapsulate related properties</strong> into one unified data type.</p> +<p>πŸ’‘ By convention, the name of the struct should follow <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a>.</p> +<p>There are 3 variants of structs,</p> +<ol> +<li><strong>C-like structs</strong></li> +</ol> +<ul> +<li>One or more comma-separated name:value pairs</li> +<li>Brace-enclosed list</li> +<li>Similar to classes (without its methods) in OOP languages</li> +<li>Because fields have names, we can access them through dot notation</li> +</ul> +<ol start="2"> +<li><strong>Tuple structs</strong></li> +</ol> +<ul> +<li>One or more comma-separated values</li> +<li>A parenthesized list like tuples</li> +<li>Looks like a named tuples</li> +</ul> +<ol start="3"> +<li><strong>Unit structs</strong></li> +</ol> +<ul> +<li>A struct with no members at all</li> +<li>It defines a new type but it resembles an empty tuple, ()</li> +<li>Rarely in use, useful with generics</li> +</ul> +<p>⭐️ When regarding OOP in Rust, attributes and methods are placed separately on <strong>structs</strong> and <strong>traits</strong>. Structs contain only attributes, traits contain only methods. They are getting connected via <strong>impls</strong>.</p>Unwrap and Expecthttps://learning-rust.github.io/docs/unwrap-and-expect/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/unwrap-and-expect/<h2 id="unwrap">unwrap()</h2> +<ul> +<li>If an <code>Option</code> type has <strong><code>Some</code></strong> value or a <code>Result</code> type has a <strong><code>Ok</code></strong> value, <strong>the value inside them</strong> passes to the next step.</li> +<li>If the <code>Option</code> type has <strong><code>None</code></strong> value or the <code>Result</code> type has <strong><code>Err</code></strong> value, <strong>program panics</strong>; If <code>Err</code>, panics with the error message.</li> +</ul> +<p>The functionality is bit similar to the following codes, which are using <code>match</code> instead <code>unwrap()</code>.</p> +<p>Example with <code>Option</code> and <code>match</code>, before using <code>unwrap()</code></p>Usehttps://learning-rust.github.io/docs/use/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/use/<p>Let&rsquo;s see the main usages of the <code>use</code> keyword.</p> +<h2 id="01-bind-a-full-path-to-a-new-name">01. Bind a full path to a new name</h2> +<p>Mainly <code>use</code> keyword is used to bind a full path of an element to a new name. So the user doesn’t want to repeat the full path each time.</p> +<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// -- Initial code without the `use` keyword -- +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">&#34;Hello, world!&#34;</span><span class="p">);</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> </span><span class="c1">// Using full path +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// -- Usage of the `use` keyword -- +</span></span></span><span class="line"><span class="cl"><span class="c1">// 01. Create an alias for module +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 02. Create an alias for module elements +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">hello</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 03. Customize names with the `as` keyword +</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="n">greet</span><span class="p">;</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> +</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> +</span></span></span></code></pre></div><h2 id="02-import-elements-to-scope">02. Import elements to scope</h2> +<p>Another common usage of <code>use</code> is importing elements to scope. Remember that, this is also a bit similar to creating an alias and using it instead of using the full path.</p>Variable bindings, Constants & Staticshttps://learning-rust.github.io/docs/variable-bindings-constants-and-statics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/variable-bindings-constants-and-statics/<h2 id="variable-bindings-constants--statics">Variable bindings, Constants &amp; Statics</h2> +<p>⭐️ In Rust, variables are <strong>immutable by default</strong>, so we call them <strong>Variable bindings</strong>. To make them mutable, the <code>mut</code> keyword is used.</p> +<p>⭐️ Rust is a <strong>statically typed</strong> language; it checks data types at compile-time. But it <strong>doesn’t require you to actually type it when declaring variable bindings</strong>. In that case, the compiler checks the usage and sets a better data type for it. But for <strong>constants and statics, you must annotate the type</strong>. Types come after a colon(<code>:</code>).</p>Vectorshttps://learning-rust.github.io/docs/vectors/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/vectors/<p>If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of <strong>a re-sizable array</strong> but <strong>all elements must be in the same type</strong>.</p> +<p>⭐️ It’s a generic type, written as <strong><code>Vec&lt;T&gt;</code></strong>Β . T can have any type, ex. The type of a Vec of i32s is <code>Vec&lt;i32&gt;</code>. Also, Vectors always allocate their data in a dynamically allocated heap.</p>Why Rust?https://learning-rust.github.io/docs/why-rust/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/why-rust/<h2 id="history-of-rust">History of Rust</h2> +<p>Rust was initially designed and developed by former Mozilla employee <strong><a href="https://github.com/graydon" target="_blank" >Graydon Hoare</a></strong> as a personal project. Mozilla began sponsoring the project in 2009 and announced it in 2010. But the first stable release, Rust 1.0, was released on May 15, 2015.</p> +<p>Since Rust 1.0, major updates have been released as <a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#rust-editions" ><code>Editions</code></a> approximately every three years: Rust 2015 (with the release of Rust 1.0) , Rust 2018, Rust 2021, and Rust 2024, all maintaining backward compatibility.</p>Workspaceshttps://learning-rust.github.io/docs/workspaces/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/workspaces/<p>When the code base is getting larger, you might need to work with <strong>multiple crates on the same project</strong>. Rust supports this via Workspaces. You can <strong>analyze (<code>cargo check</code>), build, run tests or generate docs for all crates</strong> at once by running <code>cargo</code> commands from the project root.</p> +<p>⭐️ When working on multiple crates same time, there is a higher possibility of having shared dependencies on crates. To prevent downloading and compiling the same dependency multiple times, Rust uses a <strong>shared build directory</strong> under the project root, while running <code>cargo build</code> from the project root.</p> \ No newline at end of file diff --git a/docs/manifest.json b/docs/manifest.json new file mode 100644 index 0000000..87493f4 --- /dev/null +++ b/docs/manifest.json @@ -0,0 +1,21 @@ +{ + "name": "Learning Rust", + "short_name": "Learning Rust", + "description": "Rust Programming Language Tutorials for Everyone!", + "start_url": "/?source=pwa", + "display": "standalone", + "icons": [ + { + "src": "/favicon/android-chrome-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/favicon/android-chrome-512x512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "background_color": "#866ee7", + "theme_color": "#866ee7" +} \ No newline at end of file diff --git a/docs/sitemap.xml b/docs/sitemap.xml new file mode 100644 index 0000000..e76015b --- /dev/null +++ b/docs/sitemap.xml @@ -0,0 +1 @@ +https://learning-rust.github.io/docs/borrowing/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/2025-03-13T18:13:30+08:00https://learning-rust.github.io/categories/https://learning-rust.github.io/docs/code-organization/2022-10-22T16:55:03+08:00https://learning-rust.github.io/docs/combinators/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/comments-and-documenting-the-code/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/control-flows/2024-02-01T23:03:34+05:30https://learning-rust.github.io/docs/crates/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/custom-error-types/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/2025-03-13T18:22:59+08:00https://learning-rust.github.io/docs/enums/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/error-and-none-propagation/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/functions/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/functions-02/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/generics/2022-10-22T16:55:03+08:00https://learning-rust.github.io/docs/hello-world/2024-03-10T20:15:12+08:00https://learning-rust.github.io/docs/impls-and-traits/2024-02-02T01:29:34+09:00https://learning-rust.github.io/docs/installation/2025-03-13T18:22:59+08:00https://learning-rust.github.io/2025-03-13T18:22:59+08:00https://learning-rust.github.io/docs/lifetimes/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/modules/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/operators/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/option-and-result/2024-02-01T19:02:07+01:00https://learning-rust.github.io/docs/overview/2024-03-10T20:15:12+08:00https://learning-rust.github.io/docs/ownership/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/panicking/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/primitive-data-types/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/smart-compiler/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/std-primitives-and-preludes/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/structs/2023-11-11T20:38:50+08:00https://learning-rust.github.io/tags/https://learning-rust.github.io/docs/unwrap-and-expect/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/use/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/variable-bindings-constants-and-statics/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/vectors/2022-10-22T16:55:03+08:00https://learning-rust.github.io/docs/why-rust/2025-03-13T17:11:45+08:00https://learning-rust.github.io/docs/workspaces/2022-10-17T01:47:29+08:00 \ No newline at end of file diff --git a/docs/sw.js b/docs/sw.js new file mode 100644 index 0000000..9c27f9f --- /dev/null +++ b/docs/sw.js @@ -0,0 +1,56 @@ +const cacheName = 'learning-rust-{{ now.Format "2006-01-02" }}'; +const staticAssets = [ + './', + './index.html', + './manifest.json', + './docs/**/*', + './favicon/android-chrome-192x192.png', + './favicon/android-chrome-512x512.png', + './favicon/apple-touch-icon.png', + './favicon/favicon.ico', + './favicon/favicon-16x16.png', + './favicon/favicon-32x32.png', + './css/home.min.*.css', + './css/docs.min.*.css', + './js/home.min.*.js', + './js/docs.min.*.js', +]; + +self.addEventListener('install', async e => { + const cache = await caches.open(cacheName); + await cache.addAll(staticAssets); + return self.skipWaiting(); +}); + +self.addEventListener('activate', e => { + self.clients.claim(); +}); + +self.addEventListener('fetch', async e => { + const req = e.request; + const url = new URL(req.url); + + if (url.origin === location.origin) { + e.respondWith(cacheFirst(req)); + } else { + e.respondWith(networkFirst(req)); + } +}); + +async function cacheFirst(req) { + const cache = await caches.open(cacheName); + const cached = await cache.match(req); + return cached || fetch(req); +} + +async function networkFirst(req) { + const cache = await caches.open(cacheName); + try { + const fresh = await fetch(req); + cache.put(req, fresh.clone()); + return fresh; + } catch (e) { + const cached = await cache.match(req); + return cached; + } +} \ No newline at end of file diff --git a/docs/tags/index.xml b/docs/tags/index.xml new file mode 100644 index 0000000..6e03319 --- /dev/null +++ b/docs/tags/index.xml @@ -0,0 +1 @@ +Tags on Learning Rusthttps://learning-rust.github.io/tags/Recent content in Tags on Learning RustHugoen-US \ No newline at end of file